#128 Longest consecutive sequence
Posted yxcindy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了#128 Longest consecutive sequence相关的知识,希望对你有一定的参考价值。
两种方法:
-
先sort,再找。time complexity: O(nlogn)如果用array记录次数,space complexity是O(n)。如果只用int来记录current length以及longest length, space complexity 是O(1)
-
用hashset。Time complexity O(n), space complexity O(n).
public int longestConsecutive(int[] nums) {
Set<Integer> num_set = new HashSet<Integer>();
for (int num : nums) {
num_set.add(num);
}
int longestStreak = 0;
for (int num : num_set) {
if (!num_set.contains(num-1)) {
int currentNum = num;
int currentStreak = 1;
while (num_set.contains(currentNum+1)) {
currentNum += 1;
currentStreak += 1;
}
longestStreak = Math.max(longestStreak, currentStreak);
}
}
return longestStreak;
}
以上是关于#128 Longest consecutive sequence的主要内容,如果未能解决你的问题,请参考以下文章
128. Longest Consecutive Sequence
128. Longest Consecutive Sequence
128. Longest Consecutive Sequence
128. Longest Consecutive Sequence