日期:2014-05-20  浏览次数:20773 次

急!!算法题,好心人解答.
题目是这样的.
给出7个数字(数组),数字的范围是0-13.除了0是不确定个数的,其它数字最多出现1次.0能转化成1-13中的任何以个数字.
写除算法能判断7个数字中有5个连续数.
例如   0,1,2,3,5,7,10.     0-> 4     就变成1,2,3,4,5,7,10   那就返回   true
0,0,3,8,6,10,13               0-> 7,0-> 9就变成   3,6,7,8,9,10,13   返回   true.
如果没有连续的5个数也不能靠0的变化来拼成连续的5个数就返回   false.


急啊   ,在线等...高手相助

------解决方案--------------------
for example:

bool NumberGame(int[] array)
{
//如果不足7位返回
if (array.Length != 7) return false;
//将不为零的元素添加到一个列表中
List <int> list = new List <int> ();
foreach (int i in array)
{
if (i != 0)
{
list.Add(i);
}
}
list.Sort();
//零的个数
int zeroCount = 7 - list.Count;
//如果零的个数大于等于4,肯定满足条件,返回true
if (zeroCount > = 4) return true;
//定义一个间隔数组
int[] interval = new int[list.Count - 1];
for (int i = 0; i < list.Count - 1; i++)
{
interval[i] = list[i + 1] - list[i] - 1;
}
//求最小间隔数
int min = int.MaxValue;
for (int i = 0; i < 3; i++)
{
int total = 0;
for (int j = 0; j < 5 - zeroCount - 1; j++)
{
total += interval[j];
}
min = (total < min) ? total : min;
}
if (min <= zeroCount)
return true;
else
return false;
}

初步测试了下,好像可以..
你自己再试试看..

测试如下:

static void Main(string[] args)
{
Console.WriteLine( "请输入7个小于13的整数,且以逗号分隔: ");
string str = Console.ReadLine();
while (str != "exit ")
{
string[] s = str.Split( ', ');
if (s.Length == 7)
{
int[] array = new int[7];
for (int i = 0; i < 7; i++)
{
array[i] = Convert.ToInt32(s[i].Trim());
}
if (NumberGame(array))
{
Console.WriteLine( "满足条件 ");
}
else
{
Console.WriteLine( "不满足条件 ");
}
}
str = Console.ReadLine();
}
}
static bool NumberGame(int[] array)
{
//如果不足7位返回
if (array.Length != 7) return false;
//将不为零的元素添加到一个列表中
List <int> list = new List <int> ();
foreach (int i in array)
{
if (i != 0)
{
list.Add(i);
}
}
list.Sort();
//零的个数
int zeroCount = 7 - list.Count;
//如果零的个数大于等于4,肯定满足条件,返回true
if (zeroCount > = 4) return true;
//定义一个间隔数组
int[] interval = new int[list.Count - 1];
for (int i = 0; i < list.Count - 1; i++)