LeetCode 128: Longest Consecutive Sequence

128. Longest Consecutive Sequence

Hard

Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.

Follow up: Could you implement the O(n) solution? 

 

Example 1:

Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.

Example 2:

Input: nums = [0,3,7,2,5,8,4,6,0,1]
Output: 9

 

Constraints:

  • 0 <= nums.length <= 104
  • -109 <= nums[i] <= 109

解法1:unordered_set
参考的花生酱的网页
https://zxi.mytechroad.com/blog/hashtable/leetcode-128-longest-consecutive-sequence/
这里最关键的是           if (us.find(nums[i] - 1) == us.end()) 
这样当输入是[100,4,200,1,3,2],我们碰到4,3,2就不会再进if了,这样保证时间复杂度O(n)。

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_set us(nums.begin(), nums.end());
        int n = nums.size();
        int res = 0;
        for (int i = 0; i < n; ++i) {
            if (us.find(nums[i] - 1) == us.end()) {
                int count = 0;
                int candidate = nums[i];
                while(us.find(candidate) != us.end()) {
                    count++;
                    candidate++;
                }
                res = max(res, count);
            }
        }

        return res;
    }
};

解法2:TBD

解法3:我有个想法是用线性建堆法把nums[]建成一个最小堆,然后逐个pop,统计其中最大连续的个数。不过这样也是O(nlogn)。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值