x 128. Longest Consecutive Sequence
With range
/**
* @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;
};0
1
2
3
4
5
6
7
8
9
With Set
solutions
Last updated