简介

leetcode 128

参考链接

知乎 https://zhuanlan.zhihu.com/p/172511851

知识点总结

对于set 遍历过一次的数据进行删除, 这样就不会重复遍历数据

code

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        unordered_set<int> s;
        for(auto it: nums) s.insert(it);
        int maxV = 0;
        int sNum = s.size();
        int delN = 0;
        while(delN < sNum) {
            int value = *(s.begin());
            int it = value;
            int length = 0; 
            while(s.count(value)) {
                length++;
                s.erase(value);
                value--;
                delN++;
            }
            value = it + 1;
            while(s.count(value)) {
                length++;
                s.erase(value);
                value++;
                delN++;
            }
            maxV = max(maxV, length);
        }
        return maxV;
    }
};
posted on 2021-08-10 16:45  HDU李少帅  阅读(71)  评论(0编辑  收藏  举报