|
| 1 | +class MinHeap { |
| 2 | + constructor() { |
| 3 | + this.heap = []; |
| 4 | + this.sum = 0; |
| 5 | + this.cnt = 0; |
| 6 | + } |
| 7 | + |
| 8 | + insert(value) { |
| 9 | + this.heap.push(value); |
| 10 | + this.heapifyUp(); |
| 11 | + this.sum += value; |
| 12 | + this.cnt += 1; |
| 13 | + } |
| 14 | + |
| 15 | + heapifyUp() { |
| 16 | + let index = this.heap.length - 1; |
| 17 | + while (index > 0) { |
| 18 | + let parentIndex = Math.floor((index - 1) / 2); |
| 19 | + |
| 20 | + if (this.heap[parentIndex] <= this.heap[index]) { |
| 21 | + break; |
| 22 | + } |
| 23 | + |
| 24 | + [this.heap[parentIndex], this.heap[index]] = [ |
| 25 | + this.heap[index], |
| 26 | + this.heap[parentIndex], |
| 27 | + ]; |
| 28 | + index = parentIndex; |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + extractMin() { |
| 33 | + const min = this.heap[0]; |
| 34 | + |
| 35 | + const ok = this.heap.pop(); |
| 36 | + if (this.heap.length !== 0) this.heap[0] = ok; |
| 37 | + this.heapifyDown(); |
| 38 | + this.sum -= min; |
| 39 | + return min; |
| 40 | + } |
| 41 | + |
| 42 | + heapifyDown(index = 0) { |
| 43 | + let leftChildIndex = 2 * index + 1; |
| 44 | + let rightChildIndex = 2 * index + 2; |
| 45 | + let smallest = index; |
| 46 | + |
| 47 | + if ( |
| 48 | + leftChildIndex < this.heap.length && |
| 49 | + this.heap[leftChildIndex] < this.heap[smallest] |
| 50 | + ) { |
| 51 | + smallest = leftChildIndex; |
| 52 | + } |
| 53 | + |
| 54 | + if ( |
| 55 | + rightChildIndex < this.heap.length && |
| 56 | + this.heap[rightChildIndex] < this.heap[smallest] |
| 57 | + ) { |
| 58 | + smallest = rightChildIndex; |
| 59 | + } |
| 60 | + |
| 61 | + if (smallest !== index) { |
| 62 | + [this.heap[smallest], this.heap[index]] = [ |
| 63 | + this.heap[index], |
| 64 | + this.heap[smallest], |
| 65 | + ]; |
| 66 | + this.heapifyDown(smallest); |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + peek() { |
| 71 | + return this.heap[0]; |
| 72 | + } |
| 73 | +} |
| 74 | + |
| 75 | +function solution(scoville, K) { |
| 76 | + const minHeap = new MinHeap(); |
| 77 | + let answer = 0; |
| 78 | + |
| 79 | + // 스코빌 지수를 힙에 넣는다. |
| 80 | + scoville.forEach((v) => minHeap.insert(v)); |
| 81 | + |
| 82 | + // 힙의 최소값이 K보다 크거나 같으면 종료 |
| 83 | + while (true) { |
| 84 | + if (answer >= scoville.length) return -1; |
| 85 | + if (minHeap.peek() >= K) return answer; |
| 86 | + |
| 87 | + // 힙의 최소값 2개를 뽑아서 계산한 후 다시 넣는다. |
| 88 | + const scovil1 = minHeap.extractMin(); |
| 89 | + const scovil2 = minHeap.extractMin(); |
| 90 | + minHeap.insert(scovil1 + scovil2 * 2); |
| 91 | + |
| 92 | + // 횟수를 증가시킨다. |
| 93 | + answer++; |
| 94 | + } |
| 95 | + |
| 96 | + // 최소힙의 최소값이 K보다 크거나 같으면 answer를 리턴 |
| 97 | + return minHeap.heap[0] >= K ? answer : -1; |
| 98 | +} |
0 commit comments