Longest Consecutive Sequence

总结帖 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;
    }

 

posted @ 2015-04-19 11:46  世界到处都是小星星  阅读(121)  评论(0编辑  收藏  举报