Monday, January 14, 2019

703. Kth Largest Element in a Stream

Version #2 minHeap optimized

In previous solution, I offered the val to minHeap without checking anything
However, we can check if the coming value is larger than minHeap's peek or not to avoid meaningless offer & poll
We can see that the performance has been improved

86.26 %
class KthLargest {

    private PriorityQueue<Integer> minHeap;
private int cap;
public KthLargest(int k, int[] nums) {
minHeap = new PriorityQueue<>();
cap = k;
for (int num : nums) {
add(num);
}
}

public int add(int val) {
if (minHeap.size() < cap || val > minHeap.peek()) {
minHeap.offer(val);
}
if (minHeap.size() > cap) {
minHeap.poll();
}
return minHeap.peek();
}
}


Version #1 minHeap

16.77 %
class KthLargest {

    private PriorityQueue<Integer> minHeap;
private int cap;
public KthLargest(int k, int[] nums) {
minHeap = new PriorityQueue<>();
cap = k;
for (int num : nums) {
add(num);
}
}

public int add(int val) {
minHeap.offer(val);
if (minHeap.size() > cap) {
minHeap.poll();
}
return minHeap.peek();
}
}

No comments:

Post a Comment