Skip to content

Commit 86e88be

Browse files
committed
Added 2nd JS solution for problem 128
1 parent 8d6d40c commit 86e88be

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

javascript/128-Longest-consecutive-sequence.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,54 @@
1+
//////////////////////////////////////////////////////////////////////////////
2+
// Linear Search With A Hash Map
3+
// Time: O(n)
4+
// Space: O(n)
5+
// This solution only makes one pass over the `nums` array and is the highest
6+
// performing solution.
7+
//////////////////////////////////////////////////////////////////////////////
8+
9+
/**
10+
* @param {number[]} nums
11+
* @return {number}
12+
*/
13+
function longestConsecutive(nums) {
14+
15+
if (!nums.length) {
16+
return 0;
17+
}
18+
19+
const map = Object.create(null);
20+
let max = 0;
21+
22+
for (const num of nums) {
23+
24+
if (num in map) {
25+
continue;
26+
}
27+
28+
const prev = num - 1;
29+
const next = num + 1;
30+
let len = 1;
31+
32+
if (prev in map) {
33+
if (next in map) {
34+
len += map[prev] + map[next];
35+
map[prev - map[prev] + 1] = len;
36+
map[next + map[next] - 1] = len;
37+
} else {
38+
len += map[prev];
39+
++map[prev - map[prev] + 1];
40+
}
41+
} else if (next in map) {
42+
len += map[next];
43+
++map[next + map[next] - 1];
44+
}
45+
map[num] = len;
46+
max = Math.max(max, len);
47+
}
48+
49+
return max;
50+
}
51+
152
//////////////////////////////////////////////////////////////////////////////
253
// Linear Search With A Hash Set
354
// Time: O(n)

0 commit comments

Comments
 (0)