leetcode题解-128. Longest Consecutive Sequence

题目:给出一个没有排序的整数数组,找出最长的连续元素序列的长度。
例如,
给定[100,4,200,1,3,2],
最长的连续元素序列是[1,2,3,4]。返回它的长度:4。
你的算法应该运行在O(n)的复杂度。

分析:将所有数都加入集合或者MAP中,然后再遍历这些数。我们以MAP举例,选取关键元素向上或者向下检查有无连续值。比如选取关键元素4,先往上找,MAP中不存在5。再在MAP中往下找,依次再找到3,2,1。此时更新current_max 为4,即最大连续长度为4。值得注意的是,此时已经将元素3,2,1的value都设为1,以后这些元素不再作为关键元素查找,可以节省时间。

因为我们能O(1)的判断某个数是否在集合中,时间复杂度是O(N),空间复杂度是O(N)。

import java.util.HashMap;

public class Solution {
    // Sort & search: space O(1), time O(n logn)
    // HashMap: space O(n), time O(n)
    public static int longestConsecutive(int[] num) {
        HashMap<Integer, Integer> hs = new HashMap<Integer, Integer>();
        if(num.length == 0) return 0;
        for(int i: num){
            hs.put(i, 0);
        }
        int maxl = 1;
        for(int i: num){
            if (hs.get(i) == 1) continue;

            int tmp = i;
            int current_max = 1;
            while(hs.containsKey(tmp+1)){
                current_max ++;
                tmp ++;
                hs.put(tmp, 1);
            }

            tmp = i;
            while(hs.containsKey(tmp-1)){
                current_max ++;
                tmp --;
                hs.put(tmp, 1);
            }

            maxl = Math.max(current_max, maxl);
        }

        return maxl;
    }
    public static void main(String[] args) {
        int[] nums = {};
        System.out.println(longestConsecutive(nums));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值