2024/9/21 LeetCode Hot100 堆

This commit is contained in:
Cool 2024-09-21 23:03:49 +08:00
parent 361bd0ba38
commit ad9d3e352f
2 changed files with 115 additions and 0 deletions
src/main/java/com/cool/hot100/heap

View File

@ -0,0 +1,52 @@
package com.cool.hot100.heap;
import org.junit.Test;
import java.util.PriorityQueue;
/**
* Created with IntelliJ IDEA.
*
* @Author: Cool
* @Date: 2024/09/21/22:50
* DayNumber 2
* Hard 3
* Level 6
*/
public class MedianFinder {
private PriorityQueue<Integer> minQueue;
private PriorityQueue<Integer> maxQueue;
public MedianFinder() {
minQueue = new PriorityQueue<Integer>((a, b) -> (b - a));
maxQueue = new PriorityQueue<Integer>((a, b) -> (a - b));
}
public void addNum(int num) {
if (minQueue.isEmpty() || minQueue.peek() >= num) {
minQueue.offer(num);
if (minQueue.size() > maxQueue.size() + 1) {
maxQueue.offer(minQueue.poll());
}
} else {
maxQueue.offer(num);
if (maxQueue.size() > minQueue.size()) {
minQueue.offer(maxQueue.poll());
}
}
}
public double findMedian() {
if (minQueue.size() > maxQueue.size()) {
return minQueue.peek();
}
return (minQueue.peek() + maxQueue.peek()) / 2.0;
}
@Test
public void test(){
new MedianFinder().findMedian();
}
}

View File

@ -0,0 +1,63 @@
package com.cool.hot100.heap;
import org.junit.Test;
import java.util.*;
/**
* Created with IntelliJ IDEA.
*
* @Author: Cool
* @Date: 2024/09/21/19:27
* DayNumber 1
* Hard 2
* Level 3
*/
public class Num347 {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer,Integer> map=new HashMap<>();
for(int num:nums){
map.put(num,map.getOrDefault(num,0)+1);
}
Set<Map.Entry<Integer, Integer>> entries = map.entrySet();
List<Map.Entry<Integer,Integer>> list=new ArrayList<>(entries);
int heapSize=map.size();
buildMaxHeap(list, heapSize);
int[] res=new int[k];
int index=0;
for(int i=list.size()-1;i>=list.size()-k;i--){
res[index++]=list.get(0).getKey();
Collections.swap(list,0,i);
buildMaxHeap(list,0,--heapSize);
}
return res;
}
public void buildMaxHeap(List<Map.Entry<Integer,Integer>> list,int heapSize){
for(int i=(heapSize)/2;i>=0;i--){
buildMaxHeap(list,i,heapSize);
}
}
private void buildMaxHeap(List<Map.Entry<Integer,Integer>> list,int i,int heapSize){
int left=2*i+1,right=2*i+2,largest=i;
if(left<heapSize&&list.get(largest).getValue()<list.get(left).getValue()){
largest=left;
}
if(right<heapSize&&list.get(largest).getValue()<list.get(right).getValue()){
largest=right;
}
if(largest!=i){
Collections.swap(list,i,largest);
buildMaxHeap(list,largest,heapSize);
}
}
@Test
public void test(){
topKFrequent(new int[]{1,1,1,2,2,3},2);
}
}