【unordered_set用法】求无序数组中的最长连续序列长度

大致思路:

之前我仅仅停留在数组的层面上思考问题,怎么想都是复杂度为O(n^2),但是应该换一种容器——unordered_set

unordered_set是基于哈希表,采用的是链地址法解决冲突。用这个容器的目的在于,它的查找用find函数很方便而且查找的复杂度为O(1)!!!!这是很牛逼的地方!!!另外,使用erase函数也可以方便地对集合中的特定值元素进行删除。

所以,找到一个数,在表中删除它和它上下连成一片的数字,计算这一片有多长,更新长度最值。

AC代码:

class Solution {
public:
    int longestConsecutive(vector<int> &num) {
        int res=0;
        unordered_set<int> st(num.begin(),num.end());
        for(auto v: num)
        {
            if(find(st.begin(),st.end(),v)==st.end()) 
                continue;
            int l=v,h=v;
            st.erase(v);
            //找和它连续地连在一片的数字并从表中删除
            while(find(st.begin(),st.end(),h+1)!=st.end()) 
                st.erase(++h);
            while(find(st.begin(),st.end(),l-1)!=st.end())
                st.erase(--l);
            //计算这一片的长度 更新最值
            res = max(res, h-l+1);
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/m0_38033475/article/details/92083152