最长连续子序列
给定一个未排序的整数数组,找出最长连续序列的长度。
题目要求O(N)的序列,正解应该DSU,但是我偷个懒,写个set吧。
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
set<int>s;
for (int c : nums)s.insert(c);
int ans = 0;
for (int c : nums) {
if (s.find(c - 1) != s.end())continue;
int x = c;
while (s.find(x) != s.end())x++;
ans = max(ans, x - c);
}
return ans;
}
};