英文:
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
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);
}
英文:
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. 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);
}
答案1
得分: 0
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;
}
英文:
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:
- Length can always be one because longest consecutive sequence would always contain a single number, unless the input array is empty.
- You need to skip equal consecutive numbers, which the first if does by continuing the iteration.
- You don't need the consecutive_array, a single variable would be sufficient to hold the length of longest consecutive sequence, which the "ans" variable does.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论