题意
给定一个未排序的整数数组 nums
,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
题解
方法一:哈希表
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> num_set;
for(int num : nums)
num_set.insert(num);
int longestStreak = 0;
for(int num : num_set){
if(!num_set.count(num-1)){
int currentNum = num;
int currentStreak = 1;
while(num_set.count(currentNum+1)){
currentNum++;
currentStreak++;
}
longestStreak = max(longestStreak, currentStreak);
}
}
return longestStreak;
}
};
方法二:并查集
class Solution {
private:
unordered_map<int, int> parent, cnt;
public:
int find(int num) {
return num == parent[num] ? num : find(parent[num]);
}
int merge(int x, int y) {
x = find(x);
y = find(y);
if (x == y) return cnt[x];
cnt[x] += cnt[y];
parent[y] = x;
return cnt[x];
}
int longestConsecutive(vector<int>& nums) {
if (nums.empty()) return 0;
int ans = 1;
for (int i = 0; i < nums.size(); i++) {
parent[nums[i]] = nums[i];
cnt[nums[i]] = 1;
}
for (int i = 0; i < nums.size(); i++) {
if (cnt.count(nums[i] + 1)) {
ans = max(ans, merge(nums[i], nums[i]+1));
}
}
return ans;
}
};