算法1:
1、利用ArrayList维持一个有序队列
2、取ArrayList中位数
import java.util.*; public class Solution { //第一版 每次插入都用插入排序来排序 List<Integer> list = new ArrayList<>(); public void Insert(Integer num) { if(list.isEmpty()) { list.add(num); return; } for(int i=list.size()-1;i>=0;i--){ if(list.get(i)<=num){ list.add(i+1,num); break; }else if(i==0){ list.add(0,num); break; } } } public Double GetMedian() { if(list.size()==1) return list.get(0)+0d; int index = list.size()/2; if(list.size()%2==0){ //偶数个 return (list.get(index-1)+list.get(index))/2d; }else{ //奇数个 return list.get(index)+0d; } } }
算法2:利用大根堆小根堆配合实现(有点绕)
import java.util.*; public class Solution { //用大根堆和小根堆来配合实现,想不清楚的用几个数据演练一下就明白了 //小根堆 8765 private PriorityQueue<Integer> minHeap = new PriorityQueue<>(); //大根堆 1234 private PriorityQueue<Integer> maxHeap = new PriorityQueue<>(new Comparator<Integer>(){ public int compare(Integer o1,Integer o2){ return o2-o1; } }); //判断奇数偶数 int count = 0; public void Insert(Integer num) { if(count%2==0){ maxHeap.offer(num); minHeap.offer(maxHeap.poll()); }else{ minHeap.offer(num); maxHeap.offer(minHeap.poll()); } count++; } public Double GetMedian() { if(count%2==0){ return (minHeap.peek()+maxHeap.peek())/2.0; }else{ return minHeap.peek()+0d; } } }