Skip to content

Commit 96a9c88

Browse files
authored
[ PS ] : Longest Consecutive Sequence
1 parent b23ec77 commit 96a9c88

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* ์ฃผ์–ด์ง„ ๋ฐฐ์—ด์˜ ์ˆซ์ž๋“ค๋กœ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ๊ฐ€์žฅ ๊ธด ์—ฐ์† ์ˆ˜์—ด์˜ ๊ธธ์ด๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜
3+
* @param {number[]} nums
4+
* @return {number}
5+
*/
6+
const longestConsecutive = function(nums) {
7+
const sorted = Array.from(new Set(nums)).sort((a, b) => Number(a) - Number(b));
8+
9+
let maxLength = 0;
10+
let currentSequenceLength = 0;
11+
12+
for (let i = 0; i < sorted.length; i++) {
13+
if (i === 0) {
14+
maxLength = 1;
15+
currentSequenceLength = 1;
16+
continue;
17+
}
18+
19+
if (sorted[i] === sorted[i - 1] + 1) {
20+
currentSequenceLength += 1;
21+
} else {
22+
currentSequenceLength = 1;
23+
}
24+
25+
maxLength = Math.max(maxLength, currentSequenceLength);
26+
}
27+
28+
return maxLength;
29+
};
30+
31+
// ์‹œ๊ฐ„๋ณต์žก๋„: O(n)
32+
// ๊ณต๊ฐ„๋ณต์žก๋„: O(n)

0 commit comments

Comments
ย (0)