Leetcode (easy heap)
703 数据流中的第K大元素
class KthLargest{
int size;
private PriorityQueue<Integer> q;
public KthLargest(int k,int[] nums){
size = k;
q = new PriorityQueue(k);
for(int num:nums) add(num);
}
public int add(int val){
if(q.size()<size) q.add(val);
else if(q.peek()<val){
q.poll();
q.add(val);
}
return q.peek();
}
}
1046 最后一块石头的重量
class Solution {
public int lastStoneWeight(int[] stones) {
PriorityQueue<Integer> queue = new PriorityQueue<>((o1, o2) -> (o2 - o1));
for (int i = 0; i < stones.length; i++) {
queue.offer(stones[i]);
}
while( queue.size() > 1 ) {
int y = queue.poll();
int x = queue.poll();
int diff = y - x;
if ( diff != 0 ) queue.offer(diff);
}
if ( queue.size() == 0 ) return 0;
return queue.peek();
}
}