繁体   English   中英

从给定的未排序整数数组中查找最长连续元素序列的长度

[英]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;
}

好的,假设不必订购最长的连续序列,您可以做几件事:

  1. 长度总是可以是一,因为最长的连续序列总是包含一个数字,除非输入数组为空。
  2. 您需要跳过相等的连续数字,第一个 if 通过继续迭代来完成。
  3. 您不需要连续数组,单个变量足以保存最长连续序列的长度,“ans”变量就是这样做的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM