Longest Consecutive Sequence

来源:互联网 发布:进口儿童安全座椅知乎 编辑:程序博客网 时间:2024/06/02 01:59

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

Clarification

Your algorithm should run in O(n) complexity.

Example

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


这道题比较简单,用一个hashset把数组存入,然后再次遍历数组,然后往num[i]+1, -1两个方向去找,看在set里是否存在,如果存在,那么count++,并且将对应比他大,小的数字从set中删掉,可以避免重复计算

代码:

public int longestConsecutive(int[] num) {        // write you code here        if(num == null || num.length == 0) return 0;        HashSet<Integer> set = new HashSet<>();        for(int i=0;i<num.length;i++){            set.add(num[i]);        }                int max = 0;        //还是遍历数组,hashset不好遍历        for(int i=0;i<num.length;i++){            int count = 1;            int down = num[i]-1;            while(set.contains(down)){                //System.out.println("contains:"+down);                set.remove(down);                count++;                down--;                            }            int up = num[i]+1;            while(set.contains(up)){                set.remove(up);                count++;                up++;                            }            max = Math.max(max, count);        }        return max;    }


0 0
原创粉丝点击