Skip to content

Commit 83d3346

Browse files
committed
solve(w01): 128. Longest Consecutive Sequence
1 parent 6ca4f60 commit 83d3346

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
6+
var longestConsecutive = function(nums) {
7+
if (nums.length <= 1) return nums.length;
8+
9+
const sortedArray = [...new Set(nums)].sort((a,b) => a - b);
10+
11+
let maxLength = 1;
12+
let currentLength = 1;
13+
14+
for (let i = 1; i < sortedArray.length; i++) {
15+
if (sortedArray[i] === sortedArray[i-1] + 1) {
16+
currentLength++;
17+
} else {
18+
currentLength = 1;
19+
}
20+
21+
maxLength = Math.max(maxLength, currentLength);
22+
}
23+
24+
return maxLength;
25+
};

0 commit comments

Comments
 (0)