最长连续序列
注意:用过的元素要删除掉,否则会时间超时
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
//使用set的存储使得他不会出现重复
unordered_set<int> map_s(nums.begin(), nums.end());
int res = 0;
for (auto n : nums)
{
//如果没有这个数字的话说明被删除了
if (map_s.count(n) == 0)
continue;
map_s.erase(n);//这里要删除有的元素
int pre = n - 1;
int next = n + 1;
while (map_s.count(pre))
{
map_s.erase(pre);
--pre;
}
pre = pre + 1;
while (map_s.count(next))
{
map_s.erase(next);
++next;
}
next = next - 1;
res = res>(next - pre + 1) ? res : next - pre + 1;
}
return res;
}
};