class Heap {
constructor() {
this.heap = [[-1, -1]];
}
get length() {
return this.heap.length -1;
}
push(value) {
this.heap.push(value);
let valueIndex = this.heap.length-1
let parentIndex = Math.floor(valueIndex/2);
while(parentIndex > 0) {
if (this.heap[parentIndex][1] <= value[1]) {
break;
}
this.heap[valueIndex] = this.heap[parentIndex];
this.heap[parentIndex] = value;
valueIndex = parentIndex;
parentIndex = Math.floor(valueIndex/2);
}
}
pop() {
const minValue = this.heap[1];
this.heap[1] = this.heap[this.heap.length-1];
this.heap.length--;
this.sinkDown(1);
return minValue;
}
sinkDown(index) {
const leftChildIndex = 2 * index;
const rightChildIndex = 2 * index+1;
const length = this.heap.length;
let smallestIndex = index;
if (leftChildIndex < length && this.heap[leftChildIndex][1] < this.heap[smallestIndex][1]) {
smallestIndex = leftChildIndex;
}
if (rightChildIndex < length && this.heap[rightChildIndex][1] < this.heap[smallestIndex][1]) {
smallestIndex = rightChildIndex;
}
if (smallestIndex !== index) {
[
this.heap[index],
this.heap[smallestIndex]
] = [
this.heap[smallestIndex],
this.heap[index]
]
this.sinkDown(smallestIndex);
}
}
}
// 해당 시점에 가장 빨리 끝날 수 있는 것을 고른다.
function solution(jobs) {
jobs.sort((a,b) => b[0] - a[0]);
const legnth = jobs.length;
let timeSum = 0;
let currTime = 0;
let currEndTime = 0;
const minHeap = new Heap();
while(jobs.length > 0 || minHeap.length > 0) {
while(jobs.length>0) {
if(jobs[jobs.length-1][0] > currTime) break;
const startAbleJob = jobs.pop();
minHeap.push(startAbleJob);
}
if (minHeap.length === 0) {
currTime++;
continue;
}
const min = minHeap.pop();
currTime += min[1];
timeSum += currTime - min[0];
// currEndTime = currTime + min[1];
}
return Math.floor(timeSum/legnth);
}
}
테스트케이스를 여러개 넣어봤는데 다 맞는데 제출을 하면 1번부터 10번까지 전부 다 틀리다.. 왜 그런지를 모르겠다.. 시간이 날 때 다시 한 번 봐야겠다
다시 보니 힙에서 push를 할 때 반복문에서 올라가면서 인덱스를 올려주는 부분이 없어서 틀렸던 것이었다. 문제를 좀 더 차근차근 풀어야겠다.