|
1 |
| -// 시간 복잡도 O(n log n) |
2 |
| -// 공간 복잡도 O(n) |
3 |
| - |
4 | 1 | /**
|
5 | 2 | * @param {number[]} nums
|
6 | 3 | * @return {number}
|
7 | 4 | */
|
8 | 5 | var longestConsecutive = function(nums) {
|
9 |
| - if (nums.length === 0) return [] |
| 6 | + if (nums.length === 0) return 0; |
10 | 7 |
|
11 |
| - let maxSequenceLength = -Infinity |
| 8 | + const numSet = new Set(nums); |
| 9 | + let maxSequenceLength = 0; |
12 | 10 |
|
| 11 | + for (const num of numSet) { |
| 12 | + if (!numSet.has(num - 1)) { |
| 13 | + let currentNum = num; |
| 14 | + let currentLength = 1; |
13 | 15 |
|
14 |
| - const setNums = [...new Set(nums)].toSorted((a,b) => a - b) |
| 16 | + while (numSet.has(currentNum + 1)) { |
| 17 | + currentNum++; |
| 18 | + currentLength++; |
| 19 | + } |
15 | 20 |
|
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); |
24 | 22 | }
|
25 | 23 | }
|
26 | 24 |
|
27 |
| - return maxSequenceLength |
| 25 | + return maxSequenceLength; |
28 | 26 | };
|
29 | 27 |
|
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