看大家都是用了优先队列,我一开始没有想到没用了快速排序中partition的思想,也能完成中位数的求解
import java.util.ArrayList; import java.util.List; public class Solution { private final List<Integer> list = new ArrayList<>(); public void Insert(Integer num) { list.add(num); } public Double GetMedian() { return partition(list,0,list.size()-1); } private double partition(List<Integer> list, int lo, int hi) { int pivot = list.get(lo); int i = lo,j = hi; while(i<j){ while(i<j&&list.get(j)>pivot){ j--; } list.set(i,list.get(j)); while(i<j&&list.get(i)<pivot){ i++; } list.set(j,list.get(i)); } list.set(i,pivot); if (i<(list.size()>>1)){ return partition(list,i+1,hi); }else if(i>(list.size()>>1)){ return partition(list,lo,i-1); }else { if((list.size()%2==1)){ return list.get(j); }else{ return (list.get(j)+list.get(j-1))*0.5; } } } }