最后一块石头的重量
1046. 最后一块石头的重量 - 力扣(LeetCode)

class Solution {
public int lastStoneWeight(int[] stones) {
PriorityQueue<Integer> queue=new PriorityQueue<>((a,b)->b-a);
for(int x:stones){
queue.offer(x);
}
while(queue.size()>1){
int val1=queue.poll();
int val2=queue.poll();
if(val1>val2){
queue.offer(val1-val2);
}
}
return queue.isEmpty()?0:queue.peek();
}
}
数据流的第K大元素
703. 数据流中的第 K 大元素 - 力扣(LeetCode)

class KthLargest {
PriorityQueue<Integer> heap;
int k1;
public KthLargest(int k, int[] nums) {
k1=k;
heap=new PriorityQueue<>();
for(int x:nums){
heap.offer(x);
if(heap.size()>k1){
heap.poll();
}
}
}
public int add(int val) {
heap.offer(val);
if(heap.size()>k1){
heap.poll();
}
return heap.peek();
}
}
/**
* Your KthLargest object will be instantiated and called as such:
* KthLargest obj = new KthLargest(k, nums);
* int param_1 = obj.add(val);
*/
前K个高频单词

在单词出现的次数相同的时候,我们需要比较他们的字典序
class Solution {
public List<String> topKFrequent(String[] words, int k) {
Map<String,Integer> hash=new HashMap<>();
for(String s:words){
hash.put(s,hash.getOrDefault(s,0)+1);
}
PriorityQueue<Pair<String,Integer>> heap=new PriorityQueue<>(
(a,b)->{
if(a.getValue().equals(b.getValue())){
return b.getKey().compareTo(a.getKey());
}
return a.getValue()-b.getValue();
}
);
for(Map.Entry<String,Integer> e:hash.entrySet()){
heap.offer(new Pair<>(e.getKey(), e.getValue()));
if(heap.size()>k){
heap.poll();
}
}
List<String> ret=new ArrayList<>();
while(!heap.isEmpty()){
ret.add(heap.poll().getKey());
}
Collections.reverse(ret);
return ret;
}
}
数据流的中位数

创建一个大根堆,一个小根堆

class MedianFinder {
PriorityQueue<Integer> left;
PriorityQueue<Integer> right;
public MedianFinder() {
left=new PriorityQueue<>((a,b)->b-a);
right=new PriorityQueue<>((a,b)->a-b);
}
public void addNum(int num) {
// 长度相等
if(left.size()==right.size()){
if(left.isEmpty() || num<=left.peek()){
left.offer(num);
}else{
right.offer(num);
left.offer(right.poll());
}
}else{ // 长度不相等
if(num<=left.peek()){
left.offer(num);
right.offer(left.poll());
}else{
right.offer(num);
}
}
}
public double findMedian() {
if(left.size()==right.size()){
return (left.peek()+right.peek())/2.0;
}else{
return left.peek();
}
}
}
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder obj = new MedianFinder();
* obj.addNum(num);
* double param_2 = obj.findMedian();
*/

被折叠的 条评论
为什么被折叠?



