128. 最长连续序列——哈希

class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        if(!nums.size())
            return 0;
        unordered_set<int> numSet;
        int maxLen = 1, len;    //最大长度,临时长度
        for(auto num : nums){
            numSet.insert(num); //遍历放入numSet
        }
        for(auto num : numSet){ //依次进行最长数字序列判断
            if(!numSet.count(num - 1)){ //避免重复筛选,
                len = 1;
                int temp = num + 1;
                while(numSet.count(temp)){
                    len++;
                    temp += 1;
                }
                maxLen = max(maxLen, len);
            }
        }
        return maxLen;
    }
};

Accepted
70/70 cases passed (52 ms)
Your runtime beats 84.36 % of cpp submissions
Your memory usage beats 39.78 % of cpp submissions (30.2 MB)

你可能感兴趣的:(力扣每日刷题,哈希算法,散列表,leetcode,c++)