Skip to content

Commit e56df25

Browse files
committed
longest consecutive sequence solution
1 parent 527367f commit e56df25

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number}
4+
*/
5+
var longestConsecutive = function (nums) {
6+
7+
//엣지케이스: 빈배열인 경우
8+
if (nums.length === 0) {
9+
return 0;
10+
}
11+
12+
//Set으로 중복값 제거하기
13+
const numsSet = new Set(nums);
14+
15+
let tempMaxLength = 1;
16+
17+
for (num of numsSet) {
18+
let startPoint = num - 1;
19+
let hasStart = numsSet.has(startPoint);
20+
21+
//!hasStart인 num이 첫번째에 와야할 수니까!
22+
if (!hasStart) {
23+
24+
let currentLength = 1;
25+
26+
while (numsSet.has(num + currentLength)) {
27+
currentLength++;
28+
}
29+
// max 찾기
30+
tempMaxLength = Math.max(currentLength, tempMaxLength);
31+
} else {
32+
continue;
33+
}
34+
}
35+
36+
return tempMaxLength;
37+
38+
};

0 commit comments

Comments
 (0)