diff --git a/src/main/java/com/cool/hot100/heap/MedianFinder.java b/src/main/java/com/cool/hot100/heap/MedianFinder.java new file mode 100644 index 0000000..7ff5669 --- /dev/null +++ b/src/main/java/com/cool/hot100/heap/MedianFinder.java @@ -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 minQueue; + private PriorityQueue maxQueue; + + public MedianFinder() { + minQueue = new PriorityQueue((a, b) -> (b - a)); + maxQueue = new PriorityQueue((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(); + } +} + diff --git a/src/main/java/com/cool/hot100/heap/Num347.java b/src/main/java/com/cool/hot100/heap/Num347.java new file mode 100644 index 0000000..d1c9175 --- /dev/null +++ b/src/main/java/com/cool/hot100/heap/Num347.java @@ -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 map=new HashMap<>(); + for(int num:nums){ + map.put(num,map.getOrDefault(num,0)+1); + } + Set> entries = map.entrySet(); + List> 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> list,int heapSize){ + for(int i=(heapSize)/2;i>=0;i--){ + buildMaxHeap(list,i,heapSize); + } + } + + private void buildMaxHeap(List> list,int i,int heapSize){ + + int left=2*i+1,right=2*i+2,largest=i; + if(left