【发布时间】:2020-02-06 02:55:03
【问题描述】:
我必须创建一个函数来查找数组中最长的连续整数序列。
数组是这样的:
{1,2,3,4,4,4,5,7,9,10}
注意:跳过序列中的重复数字。
这是我的代码:
int longestSequence(const int arr[], int size)
{
int currentSeq = 1;//set to 1 because all sequences are at least 1
int maxSeq;
for (int i = 1; i < size; i++)
{
if (arr[i] == arr[i-1]);//skip repeated numbers
else if (arr[i-1] == (arr[i] - 1))//check if index is 1 greater than last
{
currentSeq++;
}
else //if not reset and hold last sequence value as max
{
maxSeq = currentSeq;
currentSeq = 1;
}
}
if (currentSeq > maxSeq) //if the last index of the array was last in the sequence
{
maxSeq = currentSeq;
}
return maxSeq;
}
我的代码一直为这个数组返回 2,但显然它应该是 5。
任何帮助将不胜感激。
【问题讨论】:
-
您总是在序列的末尾设置
maxSeq。你检查 if 对于循环外的最后一个是否真的更长。 -
@FrançoisAndrieux 感谢您的回复,但是,即使将其移动到循环中,它仍然返回 2。
-
不,您必须向
else添加条件以检查当前序列是否超过最大值。您还需要初始化maxSeq。