-
Notifications
You must be signed in to change notification settings - Fork 277
/
KthLargestElementInAStream.java
52 lines (39 loc) · 1.15 KB
/
KthLargestElementInAStream.java
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// @saorav21994
// TC : O(nlogk + mlogk)
// SC : O(k)
class KthLargest {
PriorityQueue<Integer> queue;
int maxLimit;
public KthLargest(int k, int[] nums) {
this.queue = new PriorityQueue<>(); // min-heap
this.maxLimit = k;
// restrict priority queue upto maxLimit size. top element will be answer.
for (int i = 0; i < nums.length; i++) {
if (k > 0) {
queue.offer(nums[i]);
k -= 1;
}
else {
if (nums[i] > queue.peek()) {
int getOut = queue.poll();
queue.offer(nums[i]);
}
}
}
}
public int add(int val) {
if (queue.size() < maxLimit) {
queue.offer(val);
}
else if (val > queue.peek()) {
int getOut = queue.poll();
queue.offer(val);
}
return queue.peek();
}
}
/**
* Your KthLargest object will be instantiated and called as such:
* KthLargest obj = new KthLargest(k, nums);
* int param_1 = obj.add(val);
*/