Skip to content

Commit 0c88457

Browse files
Merge pull request algorithm001#566 from SeanMrLi/master
Week_03
2 parents b6313fc + 5c077ff commit 0c88457

1 file changed

Lines changed: 91 additions & 0 deletions

File tree

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
import java.util.Comparator;
2+
import java.util.PriorityQueue;
3+
4+
/**
5+
* @author zhangruihao.zhang
6+
* @version v1.0.0
7+
* @since 2019/05/05
8+
*/
9+
public class LeetCode_703_108 {
10+
11+
12+
//方法1
13+
class KthLargest {
14+
15+
private PriorityQueue<Integer> maxHeap = null;
16+
private PriorityQueue<Integer> minHeap = null;
17+
int maxHeapCount = 0;
18+
19+
/**
20+
* 维护两个堆,大顶堆和小顶堆,小顶堆只存储k个数据,小顶堆的每个元素都大于大顶堆
21+
* 放入数据时判断,如果小于小顶堆的堆顶元素,则将堆顶放入小顶堆,调整小顶堆,否则放入大顶堆
22+
*
23+
* @param k
24+
* @param nums
25+
*/
26+
public KthLargest(int k, int[] nums) {
27+
maxHeap = new PriorityQueue<>(k, Comparator.reverseOrder());
28+
minHeap = new PriorityQueue<>();
29+
maxHeapCount = k;
30+
for (int num : nums) {
31+
add(num);
32+
}
33+
}
34+
35+
public int add(int val) {
36+
if (minHeap.size() < maxHeapCount) {
37+
minHeap.offer(val);
38+
return -1;
39+
} else if (minHeap.size() == maxHeapCount) {
40+
if (minHeap.peek() >= val) {
41+
maxHeap.offer(val);
42+
} else {
43+
maxHeap.offer(minHeap.poll());
44+
minHeap.offer(val);
45+
}
46+
}
47+
return minHeap.peek();
48+
}
49+
}
50+
51+
52+
//方法2
53+
class KthLargest {
54+
55+
private PriorityQueue<Integer> minHeap = null;
56+
int maxHeapCount = 0;
57+
58+
/**
59+
* 只维护小顶堆就可以,小顶堆只存储k个数据
60+
* 放入数据时判断,如果小于小顶堆的堆顶元素,则删除堆顶元素,同时将元素放入小顶堆,调整小顶堆
61+
*
62+
* @param k
63+
* @param nums
64+
*/
65+
public KthLargest(int k, int[] nums) {
66+
minHeap = new PriorityQueue<>();
67+
maxHeapCount = k;
68+
for (int num : nums) {
69+
add(num);
70+
}
71+
}
72+
73+
public int add(int val) {
74+
if (minHeap.size() < maxHeapCount) {
75+
minHeap.offer(val);
76+
} else if (minHeap.size() == maxHeapCount) {
77+
if (minHeap.peek() < val) {
78+
minHeap.poll();
79+
minHeap.offer(val);
80+
}
81+
}
82+
return minHeap.peek();
83+
}
84+
}
85+
86+
/**
87+
* Your KthLargest object will be instantiated and called as such:
88+
* KthLargest obj = new KthLargest(k, nums);
89+
* int param_1 = obj.add(val);
90+
*/
91+
}

0 commit comments

Comments
 (0)