Skip to content

Commit 41af5db

Browse files
feat: longest-consectuive-sequence solution
1 parent d8a48f5 commit 41af5db

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* μ •μˆ˜ λ°°μ—΄ nums
3+
* κ°€μž₯ 많이 μ—°μ†λ˜λŠ” μš”μ†Œμ˜ 길이 리턴.
4+
* O(n) μ‹œκ°„μ•ˆμ— λŒμ•„κ°€λŠ” μ•Œκ³ λ¦¬μ¦˜ μ‚¬μš©ν• κ²ƒ.
5+
*/
6+
/**
7+
* @param {number[]} nums
8+
* @return {number}
9+
*/
10+
var longestConsecutive = function (nums) {
11+
const numSet = new Set(nums);
12+
let maxCount = 0;
13+
for (let i of numSet) { //n 번 순회
14+
// ++ 이전에 연속체크가 λ˜μ—ˆμ„ 수 μžˆμœΌλ―€λ‘œ, 이전 μˆ«μžκ°€ μ‘΄μž¬ν•œλ‹€λ©΄ pass
15+
if (numSet.has(i - 1)) continue; //이미 μ§„ν–‰ 된 μ—°μ†μ²΄ν¬μ˜ 경우 ν•˜μ§€ μ•ŠλŠ”λ‹€.
16+
//연속이 λ˜λŠ”μ§€ ν™•μΈν•΄μ„œ 있으면 1μΆ”κ°€.
17+
let length = 0;
18+
while (numSet.has(i + length)) {
19+
//연속이 λŠκΈ°λŠ” μˆœκ°„ λ©ˆμΆ”λŠ” 반볡문. 즉 forλ¬Έ 전체 톡틀어 μ΅œλŒ€ n번 μ‹€ν–‰.
20+
length++;
21+
}
22+
maxCount = Math.max(length, maxCount);
23+
}
24+
return maxCount;
25+
};
26+
27+
//μ‹œκ°„λ³΅μž‘λ„ O(n) + O(n) = O(n) /κ³΅κ°„λ³΅μž‘λ„ O(n)

0 commit comments

Comments
Β (0)