leetcode-128-Longest Consecutive Sequence

#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
/*
 由于可能有负整数,所以用数组不太合适。
 用hashmap,c++用unordered_set的接口,
 保证时间复杂度为O(n)。
 遍历一次nums里的元素,如果哈希表里面有的话就找到它的相邻元素
 并把它删掉,避免下次重复重复计算。这样的话每次一找就找的是连续
 一串数。
 */
class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_set<int> myset;
        for (int i = 0; i < nums.size(); i++) {
            myset.insert(nums[i]);
        }
        int max = 0;
        while (!myset.empty()) {
            int start = *myset.begin();
            int counter = 1;
            myset.erase(start);
            int left = start - 1, right = start + 1;
            while (myset.find(left) != myset.end()) {
                myset.erase(left);
                counter++;
                left--;
            }
            while (myset.find(right) != myset.end()) {
                myset.erase(right);
                counter++;
                right++;
            }
            if (counter > max) {
                max = counter;
            }
        }
        return max;
    }
};
int main(int argc, const char * argv[]) {
    vector<int> myvec = {100, 4, 200, 1, 3, 2};
    Solution s;
    cout << s.longestConsecutive(myvec) << endl;
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值