码迷,mamicode.com
首页 > 其他好文 > 详细

Longest Consecutive Sequence

时间:2015-04-19 12:54:10      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

总结帖 http://blog.csdn.net/linhuanmars/article/details/39366817

code 参考帖 http://www.cnblogs.com/springfor/p/3869981.html

http://blog.csdn.net/linhuanmars/article/details/22964467

逻辑上很清晰,iterator的用法get

 public int longestConsecutive(int[] num) {
        if(num==null|| num.length==0) return 0;
        int  res = 1;
        HashSet<Integer> hs = new HashSet<Integer>();
        for(int i=0; i<num.length; i++){
            hs.add(num[i]);
        }
         
        while(!hs.isEmpty()){
            Iterator it  = hs.iterator();
            int item = (Integer) it.next();
            //dont forget this
            hs.remove(item);
            int cnt = 1;
            int less = item-1;
            int more = item+1;
            while(hs.contains(less)){
                cnt++;
                hs.remove(less--);
            }
            while(hs.contains(more)){
                cnt++;
                hs.remove(more++);
            }
            res = Math.max(res,cnt);
        }
        return res;
    }

 

Longest Consecutive Sequence

标签:

原文地址:http://www.cnblogs.com/jiajiaxingxing/p/4438855.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!