美文网首页
数组中最长可连续值的个数

数组中最长可连续值的个数

作者: qpan | 来源:发表于2018-04-02 10:03 被阅读5次

For example, Given [100, 4, 200, 1, 3, 2], The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.

/**
     * o(n)复杂度
     * @param arrays
     * @return
     */
   // [100, 4, 200, 1, 3, 2]--> 1,2,3,4   return 4
    public static int longestConsecutive(int[] arrays){
        final HashSet<Integer> mySet=new HashSet<>();
        for (int i:arrays){
            mySet.add(i);
        }
        int longest=0;
        for (int value:arrays){
            int length=1;
            for (int i=value-1;mySet.contains(i);--i){
                mySet.remove(i);
                ++length;
            }
            for (int i=value+1;mySet.contains(i);++i){
                mySet.remove(i);
                ++length;
            }
            longest=Math.max(longest,length);
        }
        return longest;
    }

相关文章

网友评论

      本文标题:数组中最长可连续值的个数

      本文链接:https://www.haomeiwen.com/subject/fksthftx.html