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)。
博客围绕LeetCode 128题Longest Consecutive Sequence展开,该题要求返回未排序整数数组中最长连续元素序列的长度。介绍了解法1,利用unordered_set,通过关键判断保证时间复杂度为O(n);还提及解法3,用线性建堆法建最小堆统计最大连续个数,时间复杂度为O(nlogn),解法2待确定。
647

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



