128. 最长连续序列

给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。

请你设计并实现时间复杂度为 O(n) 的算法解决此问题。

solution : 

    用一个set集合存所有元素,然后遍历每一个元素,如果当前元素n 有n-1在set集合种,那么不计数,没有就从n计数找最长连续子序列

    

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_set<int> uset(nums.begin(), nums.end());
        int result = 0;
        for (auto n : nums) {
            if (uset.find(n - 1) == uset.end()) {
                int num = n;
                int count = 1;
                while (uset.find(num + 1) != uset.end()) {
                    ++num;
                    ++count;
                }
                result = max(count, result);
            }
        }
        return result;
    }
};

 

posted @ 2022-12-28 16:17  tuffy_tc  阅读(23)  评论(0)    收藏  举报