判断这5个数值是否连续相邻

1.一个整数数列,元素取值可能是0~65535中的任意一个数,相同数值不会重复出现。0是例外,可以反复出现。
请设计一个算法,当你从该数列中随意选取5个数值,判断这5个数值是否连续相邻。
注意:
- 5个数值允许是乱序的。比如: 8 7 5 0 6
- 0可以通配任意数值。比如:8 7 5 0 6 中的0可以通配成9或者4
- 0可以多次出现。
- 复杂度如果是O(n2)则不得分。

namespace MyNameSpace

{

class MyClass

{

static void Main()

{

int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 };

int[] chars = { 9, 11, 13, 0, 0 };

System.Console.WriteLine(new MyClass().IfExist(array,chars));

System.Console.ReadKey();

}

public bool IfExist(int[] array, int[] chars)

{

if (chars.Length != 5 && array.Length < 5)

{

throw new System.FormatException("chars must have five elements and array must have at least 5 elements.");

}

for (int i = 0; i <= array.Length - 5; i++)

{

if (IfMatch(new int[] { array[i], array[i + 1], array[i + 2], array[i + 3], array[i + 4] }, chars))

{

return true;

}

}

return false;

}

private bool IfMatch(int[] chars1, int[] chars2)

{

bool[] matchResult = new bool[5];

foreach (int i in chars1)

{

for (int j = 0; j < 5; j++)

{

if (matchResult[j] == false && chars2[j] == i)

{

matchResult[j] = true;

}

}

}

for (int i = 0; i < 5; i++)

{

if (matchResult[i] == false && chars2[i] != 0)

{

return false;

}

}

return true;

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值