classMedianFinder{List<Integer> list =newArrayList<>();publicMedianFinder(){}publicvoidaddNum(int num){int i = list.size();while(i >0){if(num < list.get(i-1)){
i-=1;}else{break;}}if(i == list.size()){
list.add(num);}else{
list.add(i, num);}}publicdoublefindMedian(){int l = list.size();if(l %2==1){return list.get(l/2);}return(list.get(l/2)+ list.get(l/2-1))/2.0D;}}/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder obj = new MedianFinder();
* obj.addNum(num);
* double param_2 = obj.findMedian();
*/
最大最小堆
classMedianFinder{PriorityQueue<Integer> maxHeap =newPriorityQueue<Integer>((a, b)-> b-a);PriorityQueue<Integer> minHeap =newPriorityQueue<Integer>((a, b)-> a-b);publicMedianFinder(){}publicvoidaddNum(int num){if(maxHeap.isEmpty()|| num < maxHeap.peek()){
maxHeap.offer(num);if(minHeap.size()+1< maxHeap.size()){
minHeap.offer(maxHeap.poll());}}else{
minHeap.offer(num);if(minHeap.size()> maxHeap.size()){
maxHeap.offer(minHeap.poll());}}}publicdoublefindMedian(){if(maxHeap.size()> minHeap.size()){return maxHeap.peek();}return(minHeap.peek()+ maxHeap.peek())/2.0D;}}/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder obj = new MedianFinder();
* obj.addNum(num);
* double param_2 = obj.findMedian();
*/