Skip to content

Commit 044cdcf

Browse files
committed
longest-consecutive-sequence solution
1 parent c1838af commit 044cdcf

1 file changed

Lines changed: 27 additions & 0 deletions

File tree

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* ๋ฌธ์ œ: https://leetcode.com/problems/longest-consecutive-sequence/description/
3+
*
4+
* ์š”๊ตฌ์‚ฌํ•ญ:
5+
* ์ •๋ ฌ๋˜์ง€ ์•Š์€ nums: number[]๋ฅผ Input ์œผ๋กœ ๋ฐ›์•˜์„ ๋•Œ
6+
* ๊ฐ€์žฅ ๊ธด ์—ฐ์†์œผ๋กœ ๋œ ๊ฐ’์˜ length ๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.
7+
* ๋‹จ O(n) ์ด์–ด์•ผํ•œ๋‹ค.
8+
*
9+
* * */
10+
11+
const longestConsecutive = (nums) => {
12+
const set = new Set(nums);
13+
let count = 0;
14+
15+
for(let num of set) {
16+
if(!set.has(num-1)) {
17+
let len = 1;
18+
19+
while (set.has(num+len)) {
20+
len++;
21+
}
22+
23+
count = Math.max(count, len);
24+
}
25+
}
26+
return count;
27+
}

0 commit comments

Comments
ย (0)