题目描述
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
Your algorithm should run in O(n) complexity.
Example:
Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
思路
思路一:
每次遍历到一个数字num,根据num-1、num+1两个数字的连续数字长度来更新当前数字的连续长度。每次要更新首尾。
思路二:
所有数字放在一个set里,遍历所有数字,如果当前数字是一个左端点,寻找长度。
代码
代码一:
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
if (nums.empty()) return 0;
unordered_map<int, int> mp;
int n = nums.size();
int res = 1;
for (auto num : nums) {
if (mp[num]) continue;
mp[num] = 1;
int st = num, ed = num;
if (mp[num-1] + 1 > mp[num]) {
int cnt = mp[num-1] + 1;
mp[num] = cnt;
st = num - cnt + 1;
ed = num;
}
if (mp[num+1] + 1 > mp[num]) {
int cnt = mp[num+1] + 1;
mp[num] = cnt;
st = num;
ed = num + cnt - 1;
}
if (mp[num-1] + mp[num+1] + 1 > mp[num]) {
int cnt = mp[num-1] + mp[num+1] + 1;
mp[num] = cnt;
st = num - mp[num-1];
ed = num + mp[num+1];
}
res = max(res, mp[num]);
mp[st] = mp[num];
mp[ed] = mp[num];
}
return res;
}
};
代码二:
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
if (nums.empty()) return 0;
unordered_set<long long> st(nums.begin(), nums.end());
int res = INT_MIN;
for (auto num : st) {
if (st.count(num-1)) continue;
int l = 0;
while(st.count(num++)) l++;
res = max(res, l);
}
return res;
}
};
看这简洁的代码。。。。

本文探讨了在未排序整数数组中寻找最长连续元素序列的问题,提出了两种高效算法,一种利用哈希表更新连续长度,另一种使用集合查找左端点并计算长度,代码简洁且运行复杂度为O(n)。

被折叠的 条评论
为什么被折叠?



