首页 > 其他 > 详细

Longest Consecutive Sequence hashset

时间:2014-07-13 21:53:18      阅读:294      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣
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/

Longest Consecutive Sequence hashset,布布扣,bubuko.com

Longest Consecutive Sequence hashset

原文:http://www.cnblogs.com/hansongjiang/p/3840651.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!