题目
地址: https://leetcode.com/problems/longest-consecutive-sequence/description/
类别: Union Find
难度: Hard
描述:
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
Your algorithm should run in O(n) complexity.
分析
给定含n个元素的无序整数数组,在O(n)时间复杂度内找出最长连续元素序列长度。
例:
Input:
[100, 4, 200, 1, 3, 2]
Output:
4([1, 2, 3, 4])
思路
最暴力的方法就是对每一个位置查看以它为起点的序列长度,如果每次都是直接遍历,时间复杂度为O(n3)。因此我们需要比较好的查找方式以及减少冗余的操作。
我们利用哈希表来存储这些元素,则建立哈希表时时间复杂度为O(n), 查找为O(1),所以最后时间复杂度为O(n)。
遍历nums[0…n-1],对每个元素nums[i]:
- 若nums[i]-1在nums中,则不检查以nums[i]为起点的序列(避免冗余检查)
- 若nums[i]-1不在nums中,则检查以nums[i]为起点的递增序列是否在nums中,当不在里面时停止查找,可得到以nums[i]为起点的最长递增序列长度
比较所有位置的最长序列长度得到最大值即为最后结果。
代码:
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> hashSet(nums.begin(), nums.end());
int maxLength = 0;
int tail;
for(int n : nums) {
if(hashSet.find(n-1) == hashSet.end()) {
tail = n + 1;
while(hashSet.find(tail) != hashSet.end()) tail++;
maxLength = max(maxLength, tail - n);
} else {
maxLength = max(maxLength, 1);
}
}
return maxLength;
}
};