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; } }
http://www.programcreek.com/2013/01/leetcode-longest-consecutive-sequence-java/
Longest Consecutive Sequence hashset
时间: 2024-10-29 13:56:45