Longest Consecutive Sequence--Leetcode(Java)

来源:互联网 发布:windows自带图片编辑器 编辑:程序博客网 时间:2024/05/21 19:05

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

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

Your algorithm should run in O(n) complexity.

昨晚做的题,睡了一觉竟然不记得了。囧。看来也不能一味的赶进度。

这题就是用一个hashset存每个元素。然后traverse整个arr, 每个元素左右扫,在set里面的count就++,然后每次update一下max如果有大的话。直接上代码比较清晰。

    public int longestConsecutive(int[] num) {        if(num==null||num.length==0){            return 0;        }        int max = 0;        HashSet<Integer> set = new HashSet<Integer>();        for(int n:num){            set.add(n);        }        for(int n:num){            int left=n-1;            int right=n+1;            int count = 1;            while(set.contains(left)){                count++;                set.remove(left);                left--;            }            while(set.contains(right)){                count++;                set.remove(right);                right++;            }            max = Math.max(count,max);        }        return max;    }


0 0
原创粉丝点击