[刷题]Longest Consecutive Sequence

[LintCode]Longest Consecutive Sequence

Version 1 暴力方法 时间复杂度高

public class Solution {
    /**
     * @param nums: A list of integers
     * @return an integer
     */
    public int longestConsecutive(int[] num) {
        // 2015-09-03 暴力方法 O(nlogn) 
        // num可能含重复元素
        if (num == null || num.length == 0) {
            return -1;
        }
        Arrays.sort(num); // O(nlogn)
        // 去掉重复元素
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < num.length; i++) {
            if (i != 0 && num[i - 1] == num[i]) {
                continue;
            }
            list.add(num[i]);
        }
        
        int max = 0;
        for (int i = 0; i < list.size(); i++) {
            if (i != 0 && list.get(i) == list.get(i - 1) + 1) {
                continue;
            }
            int sum = 1;
            int index = i - 1;
            int val = list.get(i);
            while (index >= 0 && list.get(index) == val - 1) {
                sum++;
                index--;
                val--;
            }
            index = i + 1;
            val = list.get(i);
            while (index < list.size() && list.get(index) == val + 1) {
                sum++;
                index++;
                val++;
            }
            max = max < sum ? sum : max;
        }
        return max;
    }
}

Version 2 用HashMap降低时间复杂度

public class Solution {
    /**
     * @param nums: A list of integers
     * @return an integer
     */
    public int longestConsecutive(int[] num) {
        // write you code here
        // HashMap: space O(n), time O(n)
        // 用hashmap降低时间复杂度
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int i: num) {
            map.put(i, 0);
        }
        
        int rst = 1;
        // 遍历 用hashmap做记录,已经遍历的为1,没有遍历的为0
        for(int key: num) {
            if (map.get(key) == 1) continue;

            int max = 1;
            
            int tmp = key;
            while(map.containsKey(tmp+1)) {
                max++;
                tmp++;
                map.put(tmp, 1);// 1是一个标志,表示这个点已经被算过了
            }

            tmp = key;
            while(map.containsKey(tmp-1)) {
                max++;
                tmp--;
                map.put(tmp, 1);
            }
            
            map.put(key, 1);    
            rst = Math.max(max, rst);
        }

        return rst;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值