|
| 1 | +class MinHeap { |
| 2 | + constructor() { |
| 3 | + this.heap = []; |
| 4 | + } |
| 5 | + push(value) { |
| 6 | + this.heap.push(value); |
| 7 | + this.bubbleUp(); |
| 8 | + } |
| 9 | + |
| 10 | + pop() { |
| 11 | + if (this.heap.length === 1) return this.heap.pop(); |
| 12 | + const min = this.heap[0]; |
| 13 | + this.heap[0] = this.heap.pop(); |
| 14 | + this.bubbleDown(); |
| 15 | + return min; |
| 16 | + } |
| 17 | + |
| 18 | + bubbleUp() { |
| 19 | + let index = this.heap.length - 1; |
| 20 | + |
| 21 | + while (index > 0) { |
| 22 | + const parentIndex = Math.floor((index - 1) / 2); |
| 23 | + if (this.heap[parentIndex] <= this.heap[index]) break; |
| 24 | + [this.heap[parentIndex], this.heap[index]] = [ |
| 25 | + this.heap[index], |
| 26 | + this.heap[parentIndex], |
| 27 | + ]; |
| 28 | + index = parentIndex; |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + // 루트 값을 뺐을 때 재정렬 |
| 33 | + bubbleDown() { |
| 34 | + let index = 0; |
| 35 | + const length = this.heap.length; |
| 36 | + |
| 37 | + while (true) { |
| 38 | + const left = 2 * index + 1; |
| 39 | + const right = 2 * index + 2; |
| 40 | + let smallest = index; |
| 41 | + |
| 42 | + if (left < length && this.heap[left] < this.heap[smallest]) { |
| 43 | + smallest = left; |
| 44 | + } |
| 45 | + |
| 46 | + if (right < length && this.heap[right] < this.heap[smallest]) { |
| 47 | + smallest = right; |
| 48 | + } |
| 49 | + |
| 50 | + if (smallest === index) break; |
| 51 | + |
| 52 | + [this.heap[index], this.heap[smallest]] = [ |
| 53 | + this.heap[smallest], |
| 54 | + this.heap[index], |
| 55 | + ]; |
| 56 | + |
| 57 | + index = smallest; |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + least() { |
| 62 | + return this.heap[0]; |
| 63 | + } |
| 64 | + |
| 65 | + size() { |
| 66 | + return this.heap.length; |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +function solution(scoville, K) { |
| 71 | + scoville.sort((a, b) => a - b); |
| 72 | + if (scoville[0] >= K) return 0; |
| 73 | + |
| 74 | + const minHeap = new MinHeap(); |
| 75 | + scoville.forEach((s) => minHeap.push(s)); |
| 76 | + let mixCount = 0; |
| 77 | + while (minHeap.size() > 1 && minHeap.least() < K) { |
| 78 | + const first = minHeap.pop(); |
| 79 | + const second = minHeap.pop(); |
| 80 | + const newScoville = first + second * 2; |
| 81 | + minHeap.push(newScoville); |
| 82 | + mixCount++; |
| 83 | + } |
| 84 | + |
| 85 | + return minHeap.least() >= K ? mixCount : -1; |
| 86 | +} |
| 87 | + |
| 88 | +console.log(solution([1, 2, 3, 9, 10, 12], 7)); |
0 commit comments