[英]Find the length of the longest consecutive elements sequence from a given unsorted array of integers
I am having some trouble trying to find the longest consecutive elements of a sequence, and this part is the one that sorts the array and adds the length of the consecutive elements in an ArrayList.我在寻找序列中最长的连续元素时遇到了一些麻烦,这部分是对数组进行排序并在 ArrayList 中添加连续元素长度的部分。 Could someone tell me why this code is wrong?
有人能告诉我为什么这段代码是错误的吗?
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;
}
Ok, assuming longest consecutive sequence isnt has to be ordered, you can do few things:好的,假设不必订购最长的连续序列,您可以做几件事:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.