Skip to content

Commit 5a921e5

Browse files
committed
solve: longest consecutive sequence
1 parent 77d6e59 commit 5a921e5

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* TC: O(N)
3+
* SC: O(N)
4+
* nums์˜ ์ˆซ์ž์— ์ ‘๊ทผํ•˜๋Š” ํšŸ์ˆ˜๋Š” 2๋ฒˆ์—์„œ N๋งŒํผ, 4๋ฒˆ์—์„œ ์ตœ๋Œ€ N๋งŒํผ ์ž…๋‹ˆ๋‹ค.
5+
* ์ฆ‰, 2N๋ฒˆ ๋งŒํผ nums์˜ ์ˆซ์ž์— ์ ‘๊ทผํ•ฉ๋‹ˆ๋‹ค.
6+
*/
7+
8+
/**
9+
* @param {number[]} nums
10+
* @return {number}
11+
*/
12+
var longestConsecutive = function (nums) {
13+
let maxCount = 0;
14+
const obj = {};
15+
16+
// 1. ์ˆซ์ž์˜ ์กด์žฌ ์—ฌ๋ถ€๋ฅผ ํ‚ค๋กœ ์ ‘๊ทผํ•˜๊ธฐ ์œ„ํ•ด ์ €์žฅ
17+
for (const num of nums) {
18+
obj[num] = true;
19+
}
20+
21+
// 2. ์‹œ์ž‘์ ๋“ค์„ ์ฐพ๊ธฐ ์œ„ํ•ด ์ˆœํšŒ
22+
for (const num of nums) {
23+
// 3. ์—ฐ์†์ ์ธ ๋ฐฐ์—ด์˜ ์‹œ์ž‘์ ์ธ์ง€ ํ™•์ธ
24+
if (obj[num - 1]) {
25+
continue;
26+
}
27+
28+
// 4. ์—ฐ์†์ ์ธ ๋ฐฐ์—ด์˜ ์‹œ์ž‘์ ๋ถ€ํ„ฐ ๋์ ๊นŒ์ง€ ์ˆœํšŒ
29+
let count = 1;
30+
let next = num + 1;
31+
while (obj[next]) {
32+
count += 1;
33+
next += 1;
34+
}
35+
36+
// 5. ๊ฐ€์žฅ ๊ธด ๋ฐฐ์—ด์˜ ๊ธธ์ด ๊ฐฑ์‹ 
37+
maxCount = Math.max(maxCount, count);
38+
}
39+
40+
return maxCount;
41+
};

0 commit comments

Comments
ย (0)