Longest Consecutive Sequence 解答

时间:2023-03-09 22:49:31
Longest Consecutive Sequence 解答

Question

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.

Solution

一开始尝试用segment tree, heap等,发现时间复杂度不能达到线性。

后来参考别人答案,发现用HashSet计数的方法。

程序比较简单。

1. 遍历一遍数组,将所有元素存入set

2. 遍历数组。对于当前元素x,看x+1和x-1是否在set中。如果在,则remove,并且一直找到这个区间的边界。

 public class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> set = new HashSet<Integer>();
for (int i : nums) {
set.add(i);
}
int max = 0;
int count;
for (int i : nums) {
if (set.isEmpty()) {
break;
}
count = 1;
int right = i + 1;
int left = i - 1;
set.remove(i);
// find right
while (set.contains(right)) {
set.remove(right);
count++;
right++;
}
// find left
while (set.contains(left)) {
set.remove(left);
count++;
left--;
}
max = Math.max(max, count);
}
return max;
}
}