-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path128-Longest-Consecutive-Sequence.js
More file actions
41 lines (34 loc) · 1010 Bytes
/
Copy path128-Longest-Consecutive-Sequence.js
File metadata and controls
41 lines (34 loc) · 1010 Bytes
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
36
37
38
39
40
41
/**
* @param {number[]} nums
* @return {number}
*/
var longestConsecutive = function (nums) {
if (!nums.length) return 0;
// Approach 1: use sorting and tracking
// nums.sort((a, b) => a - b);
// let counter = 1, maxLength = 1;
// for (let i = 1; i < nums.length; ++i) {
// if (nums[i] === nums[i - 1]) continue;
// else if (nums[i] - nums[i - 1] === 1) {
// counter += 1;
// maxLength = Math.max(counter, maxLength);
// } else {
// counter = 1;
// }
// }
// Approach 2: use hash-set
const numSet = new Set(nums);
let maxLength = 0;
for (const num of numSet) {
if (!numSet.has(num - 1)) {
let currentNum = num;
let counter = 1;
while (numSet.has(currentNum + 1)) {
currentNum += 1;
counter += 1;
}
maxLength = Math.max(counter, maxLength);
}
}
return maxLength;
};