From a26b40eed423cd0e619f9292406f7c68f9f355c9 Mon Sep 17 00:00:00 2001 From: Jungwoo Lee <87072568+howooking@users.noreply.github.com> Date: Fri, 17 May 2024 11:31:18 +0900 Subject: [PATCH] =?UTF-8?q?[pgm]=20=EB=8D=94=20=EB=A7=B5=EA=B2=8C=20/=20le?= =?UTF-8?q?vel2=20/=20=EB=AA=BB=ED=92=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../\353\215\224 \353\247\265\352\262\214.js" | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 "howoo/\353\215\224 \353\247\265\352\262\214.js" diff --git "a/howoo/\353\215\224 \353\247\265\352\262\214.js" "b/howoo/\353\215\224 \353\247\265\352\262\214.js" new file mode 100644 index 0000000..d344cbe --- /dev/null +++ "b/howoo/\353\215\224 \353\247\265\352\262\214.js" @@ -0,0 +1,61 @@ +class MinHeap { + constructor() { + this.heap = []; + } + + // 해당힘(인데스)의 부모의 인덱스 리턴함 + getParentIndex(index) { + return Math.floor((index - 1) / 2); + } + + // 왼쪽 자식 노드 인덱스는 부모의 2배 +1 + getLeftChildIndex(index) { + return index * 2 + 1; + } + + // 오른쪽 자식 노드 인덱스는 부모의 2배 +2 + getRightChildIndex(index) { + return index * 2 + 2; + } + + // 교환 + swap(index1, index2) { + [this.heap[index1], this.heap[index2]] = [ + this.heap[index2], + this.heap[index1], + ]; + } + + // 삽입 + insert(value) { + this.heap.push(value); + this.heapifyUp(); + } + + // 힙화 시키기 + heapifyUp() { + let index = this.heap.length - 1; + + while (index > 0) { + let parentIndex = this.getParentIndex(index); + if (this.heap[parentIndex] > this.heap[index]) { + this.swap(parentIndex, index); + index = parentIndex; + } else { + break; + } + } + } + + // 최소힙 값을 없에고 다시 힙트리를 생성 + extractMin() { + if (this.heap.length === 1) return this.heap.pop(); + 성 + const newScoville = leastSpicy + secondLeastSpicy * 2; + // 힘에 넣는다. + minHeap.insert(newScoville); + mixCount++; + } + + return minHeap.peek() >= K ? mixCount : -1; +}