Skip to content

Commit 63b08ea

Browse files
committed
longest-consecutive-sequence solution
1 parent 10b4ae1 commit 63b08ea

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
var longestConsecutive = function (nums) {
6+
let result = 1;
7+
let maxLength = 1;
8+
9+
if (nums.length === 0) return 0;
10+
11+
const sortedNums = nums.sort((a, b) => a - b);
12+
13+
for (let i = 1; i < sortedNums.length; i++) {
14+
const prevNum = sortedNums[i - 1];
15+
const currentNum = sortedNums[i];
16+
17+
const diff = currentNum - prevNum;
18+
19+
if (diff === 1) {
20+
result += 1;
21+
22+
if (maxLength < result) {
23+
maxLength = result;
24+
}
25+
} else if (diff === 0) {
26+
continue;
27+
} else {
28+
result = 1;
29+
}
30+
}
31+
32+
return maxLength;
33+
};

0 commit comments

Comments
 (0)