Skip to content

Commit 8e22356

Browse files
committed
solve: longest-consecutive-sequence
1 parent b0fc4e3 commit 8e22356

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* @description
3+
* time complexity: O(n log n)
4+
* space complexity: O(n)
5+
* runtime: 57ms
6+
* 풀이 방법: 쀑볡을 μ œκ±°ν•˜κ³  μ •λ ¬ν•œ λ‹€μŒμ— μ—°μ†λœ 숫자의 개수λ₯Ό μΉ΄μš΄νŠΈν•˜μ—¬ μ΅œλŒ€κ°’μ„ λ°˜ν™˜ν•œλ‹€.
7+
* @param {number[]} nums
8+
* @return {number}
9+
*/
10+
const longestConsecutive = function (nums) {
11+
if (nums.length === 0) return 0;
12+
const sortedNums = [...new Set(nums)].sort((a, b) => a - b);
13+
14+
let maxConsecutiveCount = 1;
15+
let currentConsecutiveCount = 1;
16+
17+
for (let i = 1; i < sortedNums.length; i += 1) {
18+
if (sortedNums[i] === sortedNums[i - 1] + 1) {
19+
currentConsecutiveCount += 1;
20+
} else {
21+
currentConsecutiveCount = 1;
22+
}
23+
24+
maxConsecutiveCount = Math.max(
25+
maxConsecutiveCount,
26+
currentConsecutiveCount
27+
);
28+
}
29+
30+
return maxConsecutiveCount;
31+
};

0 commit comments

Comments
Β (0)