128. Longest Consecutive Sequence
Hard
Given an unsorted array of integers nums
, return the length of the longest consecutive elements sequence.
Follow up: Could you implement the O(n)
solution?
Example 1:
Input: nums = [100,4,200,1,3,2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]
. Therefore its length is 4.
Example 2:
Input: nums = [0,3,7,2,5,8,4,6,0,1] Output: 9
Constraints:
0 <= nums.length <= 104
-109 <= nums[i] <= 109
解法1:unordered_set
参考的花生酱的网页
https://zxi.mytechroad.com/blog/hashtable/leetcode-128-longest-consecutive-sequence/
这里最关键的是 if (us.find(nums[i] - 1) == us.end())
这样当输入是[100,4,200,1,3,2],我们碰到4,3,2就不会再进if了,这样保证时间复杂度O(n)。
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set us(nums.begin(), nums.end());
int n = nums.size();
int res = 0;
for (int i = 0; i < n; ++i) {
if (us.find(nums[i] - 1) == us.end()) {
int count = 0;
int candidate = nums[i];
while(us.find(candidate) != us.end()) {
count++;
candidate++;
}
res = max(res, count);
}
}
return res;
}
};
解法2:TBD
解法3:我有个想法是用线性建堆法把nums[]建成一个最小堆,然后逐个pop,统计其中最大连续的个数。不过这样也是O(nlogn)。