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/

原文地址:https://www.cnblogs.com/hansongjiang/p/3840651.html