题目地址
ac参考代码
class Solution {
public:
unordered_set<int> se;
int longestConsecutive(vector<int>& nums) {
int len = nums.size();
for(int i=0;i<len;i++)
{
se.insert(nums[i]);
}
int maxLen = 0;
for(int i=0;i<len;i++)
{
int tmpLen = 1;
int nowVal = nums[i];
int tmp = nowVal + 1;
while(se.count(tmp))
{
tmpLen ++;
se.erase(tmp);
tmp ++;
}
tmp = nowVal -1;
while(se.count(tmp))
{
tmpLen ++;
se.erase(tmp);
tmp --;
}
maxLen = max(tmpLen, maxLen);
}
return maxLen;
}
};
知识点
C++ 11中出现了两种新的关联容器:unordered_set和unordered_map,其内部实现与set和map大有不同,set和map内部实现是基于RB-Tree,而unordered_set和unordered_map内部实现是基于哈希表(hashtable)。
思路解决(空间换时间)
https://leetcode.com/problems/longest-consecutive-sequence/#/solutions