42626. ๋ ๋งต๊ฒ
์ฝ๋ฉํ ์คํธ ์ฐ์ต - ๋ ๋งต๊ฒ
๋ฌธ์ ์ ํ | ๋์ด๋ | ๊ฑธ๋ฆฐ ์๊ฐ | ํด๊ฒฐ ์ ๋ฌด(โ /โ) |
---|---|---|---|
ํ | lv.2 | 30๋ถ | โ |
#
์ค๊ณ ๋ฐฉ๋ฒํ์ ๊ตฌ์ฑํ๊ณ ํ์ ๋ฃจํธ(์ต์๊ฐ)์ด K๋ณด๋ค ํด ๋๊น์ง ์๊ตฌ์ฌํญ๋๋ก (์ต์๊ฐ + 2๋ฒ์งธ์ต์๊ฐ * 2)๋ฅผ ํ์ ๋ฃ๋๋ค.
ํ์ ๊ธธ์ด๊ฐ 2๋ณด๋ค ์์ ๊ฒฝ์ฐ์๋ ๋ถ๊ฐ๋ฅํ๋ฏ๋ก -1์ ๋ฆฌํดํ๋ ๊ฒ์ผ๋ก ์์ธ์ฒ๋ฆฌํ๋ค .
#
์ฝ๋#
ํ์ด์ฌimport heapq
def solution(scoville, K): heapq.heapify(scoville) count = 0
while scoville[0] < K: if len(scoville) < 2: return -1
heapq.heappush(scoville, heapq.heappop(scoville) + heapq.heappop(scoville) * 2) count += 1
return count
#
JSfunction solution(scoville, K) { let count = 0; const heap = scoville.reduce((heap, food) => { heap.insert(food); return heap; }, new MinHeap());
while (heap.getMin() < K) { if (heap.size() < 2) { return -1; }
heap.insert(heap.remove() + heap.remove() * 2); count += 1; }
return count;}
class MinHeap { constructor() { this.heap = [null]; }
getMin() { return this.heap[1]; }
size() { return this.heap.length - 1; }
insert(node) { this.heap.push(node);
if (this.heap.length > 1) { let current = this.heap.length - 1;
while ( current > 1 && this.heap[Math.floor(current / 2)] > this.heap[current] ) { [this.heap[Math.floor(current / 2)], this.heap[current]] = [ this.heap[current], this.heap[Math.floor(current / 2)], ]; current = Math.floor(current / 2); } } }
remove() { let smallest = this.heap[1];
if (this.heap.length > 2) { this.heap[1] = this.heap[this.heap.length - 1]; this.heap.splice(this.heap.length - 1);
if (this.heap.length === 3) { if (this.heap[1] > this.heap[2]) { [this.heap[1], this.heap[2]] = [this.heap[2], this.heap[1]]; } return smallest; }
let current = 1; let leftChildIndex = current * 2; let rightChildIndex = current * 2 + 1;
while ( this.heap[leftChildIndex] && this.heap[rightChildIndex] && (this.heap[current] > this.heap[leftChildIndex] || this.heap[current] > this.heap[rightChildIndex]) ) { if (this.heap[leftChildIndex] < this.heap[rightChildIndex]) { [this.heap[current], this.heap[leftChildIndex]] = [ this.heap[leftChildIndex], this.heap[current], ]; current = leftChildIndex; } else { [this.heap[current], this.heap[rightChildIndex]] = [ this.heap[rightChildIndex], this.heap[current], ]; current = rightChildIndex; }
leftChildIndex = current * 2; rightChildIndex = current * 2 + 1; } } else if (this.heap.length === 2) { this.heap.splice(1); } else { return null; }
return smallest; }}
#
์๊ฐ ๋ณต์ก๋ํ ๊ตฌ์ฑ : O(NlogN)
ํ ์ํ : O(N) (์ต์๊ฐ ์กฐํ O(1)์ ๊ฐ๋ฅ)
O(NlogN)
#
์ด๋ ค์ ๋ ์ ํ์ด์ฌ์ heapq ๋ชจ๋์ด ๋๋ฌด ํธํ๋ค.
๋ฐ๋๋ก JS์์ ํ์ ์ฐ๊ธฐ ๋๋ฌด ๋ถํธํ๋ค.
#
์ฐธ๊ณ ์๋ฃheapq --- ํ ํ ์๊ณ ๋ฆฌ์ฆ - ํ์ด์ฌ ์ค๋ช ์ ์ฃผ์ํ