LeetCode - Algorithms - 703. Kth Largest Element in a Stream

Problem

703. Kth Largest Element in a Stream

Java

priority queue - Java collections framework

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.util.PriorityQueue;

class KthLargest {
private int k;
private PriorityQueue<Integer> minHeap;

public KthLargest(int k, int[] nums) {
this.k = k;
minHeap = new PriorityQueue<Integer>(k);
for(int i : nums) {
minHeap.offer(i);
if (minHeap.size()>k)
minHeap.poll();
}
}

public int add(int val) {
minHeap.offer(val);
if (minHeap.size()>k)
minHeap.poll();
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);
*/

Submission Detail

  • 10 / 10 test cases passed.
  • Runtime: 17 ms, faster than 49.28% of Java online submissions for Kth Largest Element in a Stream.
  • Memory Usage: 44.3 MB, less than 60.24% of Java online submissions for Kth Largest Element in a Stream.