Leetcode: Longest Consecutive Sequence 理解分析

题目大意:给定一个非有序的整型数组,找出这个整型数组中最长的连续序列,返回该序列长度。

理解:最长连续序列是指数组中最长的递增序列,这个序列分散在数组中。本题大多数人包括我自己第一反应都是排序,然后扫描一遍就可以找出这个序列。但是本题要求时间复杂度控制在O(n)!所以排序就排除在外了。题目也就是要求在原数组基础上,扫描一遍然后找这个最长序列,返回其长度。

我采用的方法是用一个HashMap保存数组的值,作为map的key,对应的value则存储其所在的最长序列中的最大值。

实现:

public class Solution {
    public int longestConsecutive(int[] num) {
        int len = num.length;
        if(len == 0) return 0;
        // store the array as the key  of the map, and calculate the max consecutive value as the value
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int i = 0; i < len; i ++) {
            if(!map.containsKey(num[i])) {
                int maxConsecutive = num[i];
                map.put(num[i], num[i]);
                
                if(map.containsKey(num[i]+1)) {
                    maxConsecutive = map.get(num[i]+1);
                    map.put(num[i], maxConsecutive);
                }
                // set all the key in the consecutive as the max
                int pre = num[i] - 1;
                while(map.containsKey(pre)) {
                    map.put(pre, maxConsecutive);
                    pre --;
                }
            }
        }
        // get the max distance between the consecutive
        int min = 0, max = 0;
        for(Map.Entry<Integer,Integer> entry: map.entrySet()) {
            if(entry.getValue() - entry.getKey() > max - min) {
                max = entry.getValue();
                min = entry.getKey();
            }
        }
        return max-min+1;
    }
}

经过分析,上面的解法在最坏的情况下的时间复杂度并不是O(n),而是接近O(n^2)。例子:1,2,3,4,5,6,7.

O(n)的解法还会继续探索。


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值