128. Longest Consecutive Sequence
空间换时间,引入hash_map
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
map<int, bool> hash;
int res = 0;
for (int i = 0; i < nums.size(); i++) hash[nums[i]] = true;
for (int i = 0; i < nums.size(); i++) {
int up = nums[i] + 1;
int down = nums[i] - 1;
while (hash.count(up)) {
hash.erase(up);
up++;
}
while (hash.count(down)) {
hash.erase(down);
down--;
}
res = max(up - down - 1, res);
}
return res;
}
};