-
Notifications
You must be signed in to change notification settings - Fork 41
/
solution.js
35 lines (31 loc) · 895 Bytes
/
solution.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* @param {number[]} nums
* @return {number}
*/
const longestConsecutive = function (nums) {
const countMap = {};
const parentMap = {};
let max = 0;
for (let i = 0; i < nums.length; i++) {
if (parentMap[nums[i]] !== undefined) {
continue;
}
let count = 1;
let parentId = nums[i];
if (parentMap[nums[i] - 1] !== undefined) {
parentId = nums[i] - 1;
while (parentMap[parentId] !== parentId) {
parentId = parentMap[parentId];
}
count += countMap[parentId];
}
if (parentMap[nums[i] + 1] !== undefined) {
count += countMap[nums[i] + 1];
parentMap[nums[i] + 1] = parentId;
}
parentMap[nums[i]] = parentId;
countMap[parentId] = count;
max = Math.max(max, count);
}
return max;
};