Skip to content

Commit 9253817

Browse files
committed
Solution: Longest-consecutive-sequence
1 parent a230dab commit 9253817

1 file changed

Lines changed: 35 additions & 0 deletions

File tree

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* ์ฃผ์–ด์ง„ ์ˆซ์ž ๋ฐฐ์—ด์—์„œ ๊ฐ€์žฅ ๊ธด ์—ฐ์†๋œ ์ˆ˜์—ด์˜ ๊ธธ์ด๋ฅผ ์ฐพ๋Š”๋‹ค.
3+
* ์‹œ๊ฐ„๋ณต์žก๋„: O(n)
4+
* ์ด์œ : ๊ฐ ์ˆซ์ž๋Š” ์ตœ๋Œ€ ํ•œ ๋ฒˆ๋งŒ ์‹œ์ž‘์ ์œผ๋กœ ๊ฒ€์‚ฌ๋˜๊ณ ,
5+
* ์—ฐ์† ์ˆ˜์—ด ํƒ์ƒ‰๋„ ์ค‘๋ณต ์—†์ด ์ง„ํ–‰๋œ๋‹ค.
6+
*
7+
* @param {number[]} nums
8+
* @return {number}
9+
*/
10+
var longestConsecutive = function(nums) {
11+
12+
// ๋ฐฐ์—ด์„ Set์œผ๋กœ ๋ณ€ํ™˜
13+
const numSet = new Set(nums);
14+
15+
// ๊ฐ€์žฅ ๊ธด ์—ฐ์† ๊ธธ์ด๋ฅผ ์ €์žฅ
16+
let longest = 0;
17+
// Set์„ ์ˆœํšŒ
18+
for (let n of numSet) {
19+
// ํ˜„์žฌ ์ˆซ์ž๊ฐ€ ์—ฐ์† ์ˆ˜์—ด์˜ "์‹œ์ž‘์ "์ธ์ง€ ํ™•์ธ
20+
// n-1 ์ด ์กด์žฌํ•˜๋ฉด ์ด๋ฏธ ์•ž์— ์ „ ์ˆ˜์—ด ์กด์žฌํ•จ
21+
if (!numSet.has(n - 1)) {
22+
23+
// ์‹œ์ž‘ํ•˜๋Š” ์ˆ˜์—ด ๊ธธ์ด
24+
let length = 1;
25+
26+
// ๊ณ„์† ์กด์žฌํ•˜๋Š”์ง€ ํ™•์ธ
27+
while (numSet.has(n + length)) {
28+
length++;
29+
}
30+
// ์ง€๊ธˆ๊นŒ์ง€ ์ฐพ์€ ์ตœ๋Œ€ ๊ธธ์ด ๊ฐฑ์‹ 
31+
longest = Math.max(longest, length);
32+
}
33+
}
34+
return longest;
35+
};

0 commit comments

Comments
ย (0)