LeetCode - 128. Longest Consecutive Sequence
Thoughts:
I choose hash set to solve this problem. This problem need to be done with O(n) time complexity, so do sorting and sliding window is not a good idea (time complexity O(nlogn)). I can find a number, and make sure the number is the start number of a sequence, then, I can try to find the next number in the sequence, and so on… After found all the numbers in a sequence, then compare the current sequence length with the max sequence length until finish the whole sequences I can get.
Code:
/**
* @param {number[]} nums
* @return {number}
*/
var longestConsecutive = function (nums) {
const numsSet = new Set(nums);
let longest = 0;
for (let num of nums) {
if (!numsSet.has(num - 1)) {
let length = 1;
while (numsSet.has(num + length)) {
length++;
}
longest = Math.max(length, longest);
}
}
return longest;
};
Reference
Copyright © 2024 | All rights reserved.