/** 128. Longest consecutive Sequence * 12.31 by Mingyang * This problem uses the uniqueness of the hashset solution, can make the time complexity of O (n). * First put all num values into HashSet, and then traverse the entire array, if there is this value in HashSet, the first to find the boundary, * Find the value of the same time the found values from the set to delete, and then look up the boundary, the same should be found in the values are deleted from the set. So each element is traversed at most, with a time complexity of O (n). */ Public intLongestconsecutive (int[] num) { if(num = =NULL|| Num.length = = 0) return0; HashSet<Integer> HS =NewHashset<integer>(); for(inti = 0;i<num.length; i++) Hs.add (Num[i]); intMax = 0; for(inti=0; i<num.length; i++){ if(Hs.contains (Num[i])) {intCount = 1; Hs.remove (Num[i]); intLow = Num[i]-1; while(Hs.contains (Low)) {hs.remove (low); Low--; Count++; } intHigh = Num[i] + 1; while(Hs.contains (High)) {hs.remove (high); High++; Count++; } Max=Math.max (max, count); } } returnMax; }
Longest consecutive Sequence