[LeetCode 解题报告]128. Longest Consecutive Sequence

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

Your algorithm should run in O(n) complexity.

Example:

Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4。
class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        if (nums.empty())
            return 0;
        
        int res = 0;
        unordered_set<int> s(nums.begin(), nums.end());
        for (int i = 0; i < nums.size(); i ++) {
            if (!s.count(nums[i])) //已经被删除
                continue;
            s.erase(nums[i]);
            int pre = nums[i] - 1, next = nums[i] + 1;
            while(s.count(pre))
                s.erase(pre--); //删除连续的前一个
            while(s.count(next))
                s.erase(next++); //删除连续的后一个
            res = max(res, next - pre -1);
        }
        return res;
    }
};
发布了401 篇原创文章 · 获赞 39 · 访问量 45万+

猜你喜欢

转载自blog.csdn.net/caicaiatnbu/article/details/103746054