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;
}
}
}