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.
要达到O(N) 的复杂度,一般的 sort都不可以,所以这题用 hashset解是最好的,主要考察DS.
将给定的数存入set, 然后遍历数组, 每拿到一个数都检查他的右边和左边,并记录次数,要注意的是删除已经访问过的number, 节约时间。
time O(N), space O(N)
public class Solution {
public int longestConsecutive(int[] num) {
if (num.length == 0) return 0;
Set<Integer> set = new HashSet<>();
for (int i : num) set.add(i);
int max = 0;
for (int i = 0; i < num.length; i++) {
int j = num[i]+1, sum = 0;
while (set.contains(j)) {
set.remove(j);
sum++;
j++;
}
j = num[i];
while (set.contains(j)) {
set.remove(j);
sum++;
j--;
}
if (sum > max) max = sum ;
}
return max;
}
}