Tags: Array, Union Find, Hard
- leetcode: Longest Consecutive Sequence
- lintcode: Longest Consecutive Sequence
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.
首先看题要求,时间复杂度为
class Solution {
public int longestConsecutive(int[] nums) {
if (nums == null || nums.length <= 0) return 0;
Set<Integer> sets = new HashSet<>(nums.length);
for (int num : nums) {
sets.add(num);
}
int result = 1;
for (int num : nums) {
int seq = 1;
int right = num, left = num;
// right
while (sets.contains(++right)) {
seq++;
sets.remove(right);
}
// left
while (sets.contains(--left)) {
seq++;
sets.remove(left);
}
sets.remove(num);
if (seq > result) result = seq;
}
return result;
}
}
首先使用 HashSet 建哈希表,然后遍历数组,依次往左往右搜相邻数,搜到了就从 Set 中删除。末尾更新最大值。
时间复杂度和空间复杂度均为