|
| 1 | +package leetcode_study |
| 2 | + |
| 3 | +import io.kotest.matchers.shouldBe |
| 4 | +import org.junit.jupiter.api.Test |
| 5 | +import java.util.PriorityQueue |
| 6 | + |
| 7 | +class `top-k-frequent-elements` { |
| 8 | + |
| 9 | + fun topKFrequent(nums: IntArray, k: Int): IntArray { |
| 10 | + return third(nums, k) |
| 11 | + } |
| 12 | + |
| 13 | + // Map 정렬 |
| 14 | + private fun first(nums: IntArray, k: Int): IntArray { |
| 15 | + val map = mutableMapOf<Int, Int>() |
| 16 | + |
| 17 | + nums.forEach { |
| 18 | + map.compute(it) { _, oldValue -> |
| 19 | + if (oldValue == null) 1 |
| 20 | + else oldValue + 1 |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + return map.entries.sortedByDescending { it.value } |
| 25 | + .map { it.key } |
| 26 | + .slice(0 until k) |
| 27 | + .toIntArray() |
| 28 | + } |
| 29 | + |
| 30 | + // 우선순위 큐 사용 |
| 31 | + private fun second(nums: IntArray, k: Int): IntArray { |
| 32 | + val map = mutableMapOf<Int, Int>() |
| 33 | + |
| 34 | + nums.forEach { map.put(it, map.getOrDefault(it, 0) + 1) } |
| 35 | + |
| 36 | + val heap: PriorityQueue<Map.Entry<Int, Int>> = PriorityQueue<Map.Entry<Int, Int>> { |
| 37 | + v1, v2 -> v2.value.compareTo(v1.value) |
| 38 | + }.apply { |
| 39 | + this.addAll(map.entries) |
| 40 | + } |
| 41 | + |
| 42 | + return (0 until k).map { heap.poll().key }.toIntArray() |
| 43 | + } |
| 44 | + |
| 45 | + // 이차원배열로 빈번도 저장 |
| 46 | + private fun third(nums: IntArray, k: Int): IntArray { |
| 47 | + val map = mutableMapOf<Int, Int>() |
| 48 | + |
| 49 | + nums.forEach { map.put(it, map.getOrDefault(it, 0) + 1) } |
| 50 | + |
| 51 | + val freq = Array<MutableList<Int>>(nums.size + 1) { mutableListOf() } |
| 52 | + map.entries.forEach { |
| 53 | + val frequency = it.value |
| 54 | + freq[frequency].add(it.key) |
| 55 | + } |
| 56 | + |
| 57 | + val result = IntArray(k) |
| 58 | + var index = 0 |
| 59 | + (freq.size - 1 downTo 0).forEach { i -> |
| 60 | + freq[i].forEach { |
| 61 | + result[index++] = it |
| 62 | + if (index == k) { |
| 63 | + return result |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + return IntArray(0) |
| 69 | + } |
| 70 | + |
| 71 | + @Test |
| 72 | + fun `배열에서_가장_빈도가_높은_K개의_원소를_출력한다`() { |
| 73 | + topKFrequent(intArrayOf(1,1,1,2,2,3), 2) shouldBe intArrayOf(1,2) |
| 74 | + topKFrequent(intArrayOf(1,1,1,2,2,3,3,4), 3) shouldBe intArrayOf(1,2,3) |
| 75 | + topKFrequent(intArrayOf(2,2,3,3,1,1,4), 3) shouldBe intArrayOf(2,3,1) |
| 76 | + topKFrequent(intArrayOf(4,1,-1,2,-1,2,3), 2) shouldBe intArrayOf(-1,2) |
| 77 | + } |
| 78 | +} |
0 commit comments