forked from algorithm001/algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetcode_703_26.java
More file actions
42 lines (33 loc) · 939 Bytes
/
Copy pathLeetcode_703_26.java
File metadata and controls
42 lines (33 loc) · 939 Bytes
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
package com.fanlu.leetcode.heap;
import java.util.PriorityQueue;
// Source : https://leetcode.com/problems/kth-largest-element-in-a-stream/
// Id : 703
// Author : Fanlu Hai
// Date : 2018-05-05
// Other : should implement priority queue manually
// Tips :
public class KthLargest {
private PriorityQueue<Integer> minHeap = new PriorityQueue<>();
private int size;
public KthLargest(int k, int[] nums) {
this.size = k;
for (int n : nums) {
add(n);
}
}
//99.55% 64.02%
public int add(int val) {
if (minHeap.size() < size)
minHeap.offer(val);
else if (minHeap.peek() < val) {
minHeap.poll();
minHeap.offer(val);
}
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);
*/