Skip to content

Commit 0e74592

Browse files
committed
feat: O(n) 풀이방법으로 변경
1 parent 1f39448 commit 0e74592

File tree

1 file changed

+15
-18
lines changed

1 file changed

+15
-18
lines changed
Lines changed: 15 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,29 @@
1-
// 시간 복잡도 O(n log n)
2-
// 공간 복잡도 O(n)
3-
41
/**
52
* @param {number[]} nums
63
* @return {number}
74
*/
85
var longestConsecutive = function(nums) {
9-
if (nums.length === 0) return []
6+
if (nums.length === 0) return 0;
107

11-
let maxSequenceLength = -Infinity
8+
const numSet = new Set(nums);
9+
let maxSequenceLength = 0;
1210

11+
for (const num of numSet) {
12+
if (!numSet.has(num - 1)) {
13+
let currentNum = num;
14+
let currentLength = 1;
1315

14-
const setNums = [...new Set(nums)].toSorted((a,b) => a - b)
16+
while (numSet.has(currentNum + 1)) {
17+
currentNum++;
18+
currentLength++;
19+
}
1520

16-
let count = 0;
17-
for (let i = 0 ; i < setNums.length; i++) {
18-
if (setNums[i]+1 === setNums[i+1]) {
19-
count += 1
20-
} else {
21-
count += 1
22-
maxSequenceLength = Math.max(maxSequenceLength, count)
23-
count = 0;
21+
maxSequenceLength = Math.max(maxSequenceLength, currentLength);
2422
}
2523
}
2624

27-
return maxSequenceLength
25+
return maxSequenceLength;
2826
};
2927

30-
31-
console.log(longestConsecutive([100,4,200,1,3,2]))
32-
console.log(longestConsecutive([0,3,7,2,5,8,4,6,0,1]))
28+
console.log(longestConsecutive([100, 4, 200, 1, 3, 2]));
29+
console.log(longestConsecutive([0, 3, 7, 2, 5, 8, 4, 6, 0, 1]));

0 commit comments

Comments
 (0)