![](/img/trans.png)
[英]Write a program to find length of longest consecutive sequence in array of integers?
[英]Find the length of the longest consecutive elements sequence from a given unsorted array of integers
我在寻找序列中最长的连续元素时遇到了一些麻烦,这部分是对数组进行排序并在 ArrayList 中添加连续元素长度的部分。 有人能告诉我为什么这段代码是错误的吗?
public static int longest_sequence(int[] array)
{
int length = 0;
// ArrayList to hold all lengths
ArrayList<Integer> consecutiveArray = new ArrayList<Integer>();
Arrays.sort(array);
for (int i = 0; i < array.length - 1; i++)
{
if (array[i] + 1 == array[i + 1])
{
length++;
}
else
{
consecutiveArray.add(length);
length = 0;
}
}
Collections.sort(consecutiveArray);
return consecutiveArray.get(consecutiveArray.size() - 1);
}
public static int longest_sequence(int[] array) {
if (array.length == 0)
return 0;
int length = 1;
int ans = 1;
Arrays.sort(array);
for (int i = 0; i < array.length - 1; i++)
{
if(array[i] == array[i+1]) {
continue;
}
else if (array[i] + 1 == array[i + 1])
{
length++;
}
else
{
length = 1;
}
ans = Math.max(ans,length);
}
return ans;
}
好的,假设不必订购最长的连续序列,您可以做几件事:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.