Leetcode213: Longest Consecutive Sequence

243 篇文章 0 订阅

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

For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.

Your algorithm should run in O(n) complexity.

一看呢,就是排序,然后找就好了,但是要求是O(n),排序明显是个O(n*logn)的算法.

只是找连续的嘛,我们可以把所有的数字都存入hash表,然后随意从某个数字开始找他的前面和后面那个是否存在.

然后得到一个最大的长度.当然找过的就可以删掉了...你想,一个连续的序列,你从中间任意位置开始往两边找不都一样么.

所以只要找过就可以删掉了.

class Solution {
public:
    unordered_set<int> s;
    int check(int a, bool direct)
    {
        int cnt = 0;
        for(auto iter = s.find(a); iter != s.end(); iter = s.find(a))
        {
            s.erase(iter);
            if(direct)  a--;
            else    a++;
            cnt++;
        }
        return cnt;
    }
public:
    int longestConsecutive(vector<int>& nums) {
        int n = nums.size();
        for(int i = 0; i < n; i++)
        {
            s.insert(nums[i]);
        }
        int ans = 0;
        for(int i = 0; i < n; i++)
        {
            ans = max(ans, check(nums[i], true)+check(nums[i]+1, false));
        }
        return ans;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值