leetcode Longest Consecutive Sequence

#include <iostream>
#include <vector>
#include <unordered_map>

// 时间复杂度是O(n), 空间复杂度O(n)
using namespace std;

class Solution1
{
public:
    int longestConsecutive(const vector<int> &nums)
    {
        unordered_map<int, bool> used;
        for (auto i: nums) used[i] = false;       // 自动匹配变量类型  建立一个 hash map

        int longest=0;
        for (auto i:nums)
        {
            if(used[i])       // true
                continue;

            int length=1;
            used[i] = true;

            for(int j=i+1; used.find(j) != used.end(); ++j)
            {
                used[j] = true;   // 向两边查找,找到了就置true,继续查找. 找不到就退出循环
                ++length;
            }

            for (int j=i-1; used.find(j) != used.end(); --j)
            {
                used[j] = true;
                ++length;
            }

            longest = max(longest, length);
        }
        return longest;
    }
};

int main()
{
    vector<int> nums={100, 4, 200, 1, 3, 2};
    Solution1 s;
    int length;
    length = s.longestConsecutive(nums);
    cout << length << endl;
}


原文地址:https://www.cnblogs.com/o-v-o/p/9980307.html