|
| 1 | +/** |
| 2 | + * @description |
| 3 | + * time complexity: O(n log n) |
| 4 | + * space complexity: O(n) |
| 5 | + * runtime: 57ms |
| 6 | + * ํ์ด ๋ฐฉ๋ฒ: ์ค๋ณต์ ์ ๊ฑฐํ๊ณ ์ ๋ ฌํ ๋ค์์ ์ฐ์๋ ์ซ์์ ๊ฐ์๋ฅผ ์นด์ดํธํ์ฌ ์ต๋๊ฐ์ ๋ฐํํ๋ค. |
| 7 | + * @param {number[]} nums |
| 8 | + * @return {number} |
| 9 | + */ |
| 10 | +const longestConsecutive = function (nums) { |
| 11 | + if (nums.length === 0) return 0; |
| 12 | + const sortedNums = [...new Set(nums)].sort((a, b) => a - b); |
| 13 | + |
| 14 | + let maxConsecutiveCount = 1; |
| 15 | + let currentConsecutiveCount = 1; |
| 16 | + |
| 17 | + for (let i = 1; i < sortedNums.length; i += 1) { |
| 18 | + if (sortedNums[i] === sortedNums[i - 1] + 1) { |
| 19 | + currentConsecutiveCount += 1; |
| 20 | + } else { |
| 21 | + currentConsecutiveCount = 1; |
| 22 | + } |
| 23 | + |
| 24 | + maxConsecutiveCount = Math.max( |
| 25 | + maxConsecutiveCount, |
| 26 | + currentConsecutiveCount |
| 27 | + ); |
| 28 | + } |
| 29 | + |
| 30 | + return maxConsecutiveCount; |
| 31 | +}; |
| 32 | + |
| 33 | +/** |
| 34 | + * @description |
| 35 | + * time complexity: O(n) |
| 36 | + * space complexity: O(n) |
| 37 | + * runtime: 36ms |
| 38 | + * ํ์ด ๋ฐฉ๋ฒ: ์ค๋ณต์ ์ ๊ฑฐํ๊ณ Set์ ์ฌ์ฉํ์ฌ O(1) ์กฐํ ๊ฐ๋ฅํ๋๋ก ํ ๋ค์์ ์ฐ์๋ ์ซ์์ ๊ฐ์๋ฅผ ์นด์ดํธํ์ฌ ์ต๋๊ฐ์ ๋ฐํํ๋ค. |
| 39 | + * @param {number[]} nums |
| 40 | + * @return {number} |
| 41 | + */ |
| 42 | +const longestConsecutive2 = function (nums) { |
| 43 | + if (nums.length === 0) return 0; |
| 44 | + |
| 45 | + // Set์ ์ฌ์ฉํ์ฌ O(1) ์กฐํ ๊ฐ๋ฅ |
| 46 | + const numSet = new Set(nums); |
| 47 | + let maxLength = 0; |
| 48 | + |
| 49 | + for (const num of numSet) { |
| 50 | + // ํ์ฌ ์ซ์๊ฐ ์ฐ์ ์์ด์ ์์์ ์ธ์ง ํ์ธ |
| 51 | + // num-1์ด ์กด์ฌํ์ง ์์ผ๋ฉด num์ด ์์์ |
| 52 | + if (!numSet.has(num - 1)) { |
| 53 | + let currentNum = num; |
| 54 | + let currentLength = 1; |
| 55 | + |
| 56 | + // ์ฐ์๋ ๋ค์ ์ซ์๋ค์ด ์กด์ฌํ๋ ๋์ ๊ณ์ ํ์ |
| 57 | + while (numSet.has(currentNum + 1)) { |
| 58 | + currentNum += 1; |
| 59 | + currentLength += 1; |
| 60 | + } |
| 61 | + |
| 62 | + // ์ต๋ ๊ธธ์ด ์
๋ฐ์ดํธ |
| 63 | + maxLength = Math.max(maxLength, currentLength); |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + return maxLength; |
| 68 | +}; |
0 commit comments