MCPcopy Create free account
hub / github.com/Tiwarishashwat/InterviewCodes / KthLargest

Class KthLargest

KthLargestElementInAStream.java:1–21  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1class KthLargest {
2 PriorityQueue<Integer> pq;
3 int k;
4 public KthLargest(int k, int[] nums) {
5 this.k = k;
6 pq = new PriorityQueue<>();
7 for(int num : nums){
8 add(num);
9 }
10 }
11
12 public int add(int val) {
13 if(pq.size()<k || val > pq.peek()){
14 pq.offer(val);
15 if(pq.size()>k){
16 pq.poll();
17 }
18 }
19 return pq.peek();
20 }
21}
22
23/**
24 * Your KthLargest object will be instantiated and called as such:

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected