Closed congr closed 5 years ago
K sized min heap
Keeping track of min heap which is size K.
class KthLargest {
PriorityQueue<Integer> minHeap;
int k;
public KthLargest(int k, int[] nums) {
this.k = k;
minHeap = new PriorityQueue<Integer>(k);
for(int n : nums) add(n); // !!! k sized min heap
System.out.println(minHeap);
}
public int add(int val) {
if (minHeap.size() < this.k) minHeap.add(val);
else if (val > minHeap.peek()) {
minHeap.remove();
minHeap.add(val);
}
// System.out.println("return " + minHeap.peek());
return minHeap.peek();
}
}
/**
* Your KthLargest object will be instantiated and called as such:
* KthLargest obj = new KthLargest(k, nums);
* int param_1 = obj.add(val);
*/