首页 > 代码库 > Longest Consecutive Sequence hashset

Longest Consecutive Sequence hashset

public class Solution {       public int longestConsecutive(int[] num) {        HashSet<Integer> hash=new HashSet<Integer>();        int max=1;        for(int n:num)        {            hash.add(n);        }        int j=0;        while(!hash.isEmpty()&&j<num.length)        {           // if(!hash.contains(num[j])) continue;            int count=1;                       int k=num[j]+1;            while(hash.contains(k))            {                hash.remove(k);              k=k+1;                   count++;                                        }            k=num[j]-1;            while(hash.contains(k))            {                hash.remove(k);                k=k-1;                count++;            }             hash.remove(num[j]);                         if(count>max) max=count;            j++;                                    }                        return max;                                            }}
View Code

 http://www.programcreek.com/2013/01/leetcode-longest-consecutive-sequence-java/