题目中提及空间复杂度不能超过O(n) 所以不能进行排序(快排为O(nlog(n)) 巧妙之处在于: if(mySet.find(num - 1) != mySet.end()) { continue; }
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> mySet;
for(int num : nums) {
mySet.insert(num);
}
int maxlen = 0;
for(int num : mySet) {
// 不用管这个数。假如当前是4,为true则表明3在这里面
// 当mySet遍历到3,自然会算进去,而且比4的长度大1
if(mySet.find(num - 1) != mySet.end()) {
continue;
}
int len = 1;
while(mySet.find(num + 1) != mySet.end()) {
num++;
len++;
}
maxlen = max(len, maxlen);
}
return maxlen;
}
};