Priority Queue implementatio with Max heap
by rishul matta
JavaScript
/**
* @param {string[]} words
* @param {number} k
* @return {string[]}
*/
var topKFrequent = function(words, k) {
class MaxHeap {
constructor(items) {
this.items = items;
}
add(node) {
this.items.push(node);
this.heapify()
}
getMax() {
const max = this.items[0];
this.items[0] = this.items.pop();
this.heapifyDown()
return max;
}
heapifyDown() {
let index = 0;
while(this.items[this.leftChild(index)] !== undefined) {
const leftChildIndex = this.leftChild(index);
const rightChildIndex = this.rightChild(index);
const leftChild = this.items[leftChildIndex];
const rightChild = this.items[rightChildIndex];
const greaterIndex = this.isGreater(leftChildIndex, rightChildIndex) ? leftChildIndex: rightChildIndex;
if (this.isGreater(index, greaterIndex)) {
break;
}
[this.items[index], this.items[greaterIndex]] = [this.items[greaterIndex], this.items[index]];
index = greaterIndex;
}
}
rightChild(index) {
return 2*index + 2;
}
leftChild(index) {
return 2*index + 1;
}
isGreater(first, second) {
if (this.items[first] === undefined) {
return false;
}
if (this.items[second] === undefined) {
return true;
}
if (this.items[first].getPriority() > this.items[second].getPriority()) {
return true;
}
if...