从零开始的LeetCode刷题日记:128. 最长连续序列

一.相关链接

题目链接:128. 最长连续序列

二.心得体会

       这道题要求时间复杂度是O(n),这就告诉我们不能用排序的方法来做。

       如果这道题用排序的方法,那么就比较简单,只需要在排序之后便利整个数组,当找到有比当前索引元素值小1的数则插入<nums[i], iter->second + 1>。否则插入<nums[i], 1>。

       不使用排序的方法需要先对vector进行去重,然后选择性地对数组中元素进行遍历统计:只有当没有前置元素的时候,才进行向后遍历,统计连续序列长度。

三.代码

1)使用排序的代码:

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        unordered_map<int,int> m;
        for(int i : nums) {
            auto iter = m.find(i - 1);
            if(iter!=m.end()) {
                m.insert(pair<int,int>(i, iter->second + 1));
            }
            else m.insert(pair<int,int>(i, 1));
        }
        int ans = 0;
        for(int i : nums) {
            if(m[i] > ans) ans = m[i];
        }
        return ans;
    }
};

2)不使用排序:

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_set<int> num_set;
        //去重
        for(const int& num : nums) {
            num_set.insert(num);
        }
        int ans = 0;

        for(const int& num : num_set) {
            if(!num_set.count(num - 1)) {
                int tem_ans = 1;
                int tem_num = num + 1;
                while(num_set.count(tem_num)) {
                    tem_ans++;
                    tem_num++;
                }
                if(tem_ans > ans) ans = tem_ans;
            }
        }
        return ans;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值