|
| 1 | +package leetcode_study |
| 2 | + |
| 3 | +import io.kotest.matchers.shouldBe |
| 4 | +import org.junit.jupiter.api.Test |
| 5 | +import kotlin.math.max |
| 6 | + |
| 7 | +/** |
| 8 | + * Leetcode |
| 9 | + * 128. Longest Consecutive Sequence |
| 10 | + * Medium |
| 11 | + */ |
| 12 | +class LongestConsecutiveSequence { |
| 13 | + /** |
| 14 | + * Runtime: 58 ms(Beats: 79.06 %) |
| 15 | + * Time Complexity: O(n) |
| 16 | + * - while 루프의 총 반복 횟수는 n을 넘을 수 없다. |
| 17 | + * |
| 18 | + * Memory: 62.65 MB(Beats: 10.48 %) |
| 19 | + * Space Complexity: O(n) |
| 20 | + */ |
| 21 | + fun longestConsecutive(nums: IntArray): Int { |
| 22 | + val numsSet: MutableSet<Int> = nums.toHashSet() |
| 23 | + val startSet: MutableSet<Int> = hashSetOf() |
| 24 | + |
| 25 | + // 수열의 시작점이 될 수 있는 수를 찾는다. |
| 26 | + for (num in numsSet) { |
| 27 | + if (!numsSet.contains(num - 1)) { |
| 28 | + startSet.add(num) |
| 29 | + } |
| 30 | + } |
| 31 | + var answer = 0 |
| 32 | + for (start in startSet) { |
| 33 | + // 수열의 시작점부터 몇 개 까지 numsSet에 있는지 확인한다. |
| 34 | + var count = 0 |
| 35 | + var first = start |
| 36 | + while (numsSet.contains(first)) { |
| 37 | + first++ |
| 38 | + count++ |
| 39 | + } |
| 40 | + // 최대 수열의 개수를 업데이트한다. |
| 41 | + answer = max(answer, count) |
| 42 | + } |
| 43 | + return answer |
| 44 | + } |
| 45 | + |
| 46 | + /** |
| 47 | + * 위 풀이에서 startSet을 제거하여 공간적으로 효율적인 풀이 |
| 48 | + * Runtime: 63 ms(Beats: 65.70 %) |
| 49 | + * Time Complexity: O(n) |
| 50 | + * |
| 51 | + * Memory: 58.47 MB(Beats: 70.81 %) |
| 52 | + * Space Complexity: O(n) |
| 53 | + */ |
| 54 | + fun longestConsecutive2(nums: IntArray): Int { |
| 55 | + val numsSet = nums.toHashSet() |
| 56 | + var maxLength = 0 |
| 57 | + |
| 58 | + for (num in numsSet) { |
| 59 | + if (!numsSet.contains(num - 1)) { |
| 60 | + var currentNum = num |
| 61 | + var currentLength = 0 |
| 62 | + |
| 63 | + while (numsSet.contains(currentNum)) { |
| 64 | + currentLength++ |
| 65 | + currentNum++ |
| 66 | + } |
| 67 | + maxLength = max(maxLength, currentLength) |
| 68 | + } |
| 69 | + } |
| 70 | + return maxLength |
| 71 | + } |
| 72 | + |
| 73 | + @Test |
| 74 | + fun test() { |
| 75 | + longestConsecutive(intArrayOf(100, 4, 200, 1, 3, 2)) shouldBe 4 |
| 76 | + longestConsecutive(intArrayOf(0, 3, 7, 2, 5, 8, 4, 6, 0, 1)) shouldBe 9 |
| 77 | + |
| 78 | + longestConsecutive2(intArrayOf(100, 4, 200, 1, 3, 2)) shouldBe 4 |
| 79 | + longestConsecutive2(intArrayOf(0, 3, 7, 2, 5, 8, 4, 6, 0, 1)) shouldBe 9 |
| 80 | + } |
| 81 | +} |
0 commit comments