标签:max dir str tco com nlog += turn hash
两种方法:
先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
标签:max dir str tco com nlog += turn hash
原文地址:https://www.cnblogs.com/yxcindy/p/9938764.html