题目描述
给定一个未排序的整数数组,找出最长连续序列的长度。
要求算法的时间复杂度为 O(n)。
示例:
输入: [100, 4, 200, 1, 3, 2]
输出: 4
解释: 最长连续序列是 [1, 2, 3, 4]。它的长度为 4。
通过次数26,033提交次数54,315
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-consecutive-sequence
思路
-
因为时间复杂度是O(n),所以不能先进行排序;
-
时间复杂度是O(n),那么考虑使用哈希表,用一个哈希表
unordered_map<int, bool> used
表示该数字是否已经计算过,然后以该数字为中心向左右扩张,知道不连续为止; -
使用动态规划:dp[i]表示在当前已经访问的数据中,该数字的最长连续序列。如[100, 4, 200, 1, 3, 2]
dp[100] = 1, dp[4] = 1, dp[200] = 1, dp[1] = 1, dp[3] = dp[4] + 1 = 2, dp[2] = dp[3] + dp[1] + 1 = 4。
-
采用类似聚类的操作
例如:[100, 4, 200, 1, 3, 2],定义一个哈希表
unordered_map<int, int> map
来表示当前数字向左右延伸后的最长连续序列 长度。访问100==>map[100] = 1;
访问4 ==>map[4] = 1;
访问200==>map[200] = 1;
访问1==> map[1] = 1;
访问3==> map[3] = 1==>map[2] 不存在, map[4]存在,将map[4] 和map[3] 数值改为{3, 4}这个序列长度2;
访问2==> map[2] = 1==>map[1], map[3]均存在,首先将map[1]和map[2]数值改为{1,2}这个序列的长度2;然后将map[2]和map[3]数值改为{1,2,3,4}这个序列的长度4。
c++
// 方法一
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_map<int, bool> used;
for(auto i : nums)
used[i] = false;
int longest = 0;
for(auto i : nums){
if(used[i])
continue;
int length = 1;
used[i] = true;
for(int j = i + 1; used.find(j) != used.end(); j++){
used[j] = true;
length ++;
}
for(int j = i - 1; used.find(j) != used.end(); j--){
used[j] = true;
length ++;
}
longest = max(longest, length);
}
return longest;
}
};
// 方法二
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_map<int, int> dp;
int ret = 0;
for(auto x : nums) {
if(!dp[x])
dp[x - dp[x - 1]] = dp[x + dp[x + 1]] = dp[x] = dp[x - 1] + dp[x + 1] + 1;
ret = max(ret, dp[x]);
}
return ret;
}
};
class Solution {
public:
int longestConsecutive(vector<int> &nums) {
unordered_map<int, int> map;
int size = nums.size();
int l = 1;
for (int i = 0; i < size; i++) {
if (map.find(nums[i]) != map.end())
continue;
map[nums[i]] = 1;
if (map.find(nums[i] - 1) != map.end()) {
l = max(l, mergeCluster(map, nums[i] - 1, nums[i]));
}
if (map.find(nums[i] + 1) != map.end()) {
l = max(l, mergeCluster(map, nums[i], nums[i] + 1));
}
}
return size == 0 ? 0 : l;
}
private:
int mergeCluster(unordered_map<int, int> &map, int left, int right) {
int upper = right + map[right] - 1;
int lower = left - map[left] + 1;
int length = upper - lower + 1;
map[upper] = length;
map[lower] = length;
return length;
}
};