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

128 Longest Consecutive Sequence

时间:2015-05-29 11:29:33      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:

public class Solution {
    public int longestConsecutive(int[] nums) {
        HashMap<Integer, Integer> hs = new HashMap<Integer, Integer>();
        for (int i : nums) {
            hs.put(i, 0);
        }
        int max = 1;
        
        for (int i : nums) {
            if (hs.get(i) == 1) {
                continue;
            }
            int temp = i;
            int currentMax = 1;
            while (hs.containsKey(temp+1)) {
                currentMax++;
                temp++;
                hs.put(temp, 1);
            }
            
            temp = i;
            while (hs.containsKey(temp-1)) {
                currentMax++;
                temp--;
                hs.put(temp, 1);
            }
            max = Math.max(currentMax, max);
        }
        return max;
    }
}

当成图想,对每一个i向两边扫, 用hashMap

参考九章答案,以及http://blog.csdn.net/linhuanmars/article/details/22964467

128 Longest Consecutive Sequence

标签:

原文地址:http://www.cnblogs.com/77rousongpai/p/4537783.html

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