x 128. Longest Consecutive Sequence
128. Longest Consecutive Sequence\
With range
time: O(n)
space: O(n)
/**
* @param {number[]} nums
* @return {number}
*/
var longestConsecutive = function(nums) {
const set = new Set(nums);
const ranges = {};
let max = 0;
for (const x of set) {
const left = ranges[x - 1] ?? 0;
const right = ranges[x + 1] ?? 0;
const dis = right + left + 1;
ranges[x] = dis;
max = Math.max(max, dis);
// TODO why?
ranges[x - left] = dis;
ranges[x + right] = dis;
}
return max;
};4 6 3 2 8 1 5
0
1
2
3
4
5
6
7
8
9
6
3
2
4
6
6
1
With Set
time: O(n)
Space: O(n)
solutions
Last updated