Skip to content

Commit 5406daf

Browse files
committed
longest consecutive sequence
1 parent 8541dec commit 5406daf

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// https://leetcode.com/problems/longest-consecutive-sequence/
2+
function longestConsecutive(nums: number[]): number {
3+
if (nums.length === 0) {
4+
return 0;
5+
}
6+
nums = [...new Set(nums)].sort((a, b) => a - b);
7+
let ans = 0;
8+
let left = 0, right = 1;
9+
for (let i = 0; i < nums.length; i++) {
10+
if (nums[i] + 1 === nums[i + 1]) {
11+
ans = Math.max(ans, right - left);
12+
} else {
13+
left = right;
14+
}
15+
right++;
16+
}
17+
return ans + 1;
18+
}

0 commit comments

Comments
 (0)