利用堆的性质找中位数

import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;
public class Madin {
  public static class MedianHolder {
    private PriorityQueue<Integer> maxHeap =
        new PriorityQueue<Integer>(new MaxHeapComparator());
    private PriorityQueue<Integer> minHeap =
        new PriorityQueue<Integer>(new MinHeapComparator());

    private void modifyTwoHeapSize() {
      if (this.maxHeap.size() == this.minHeap.size() + 2) {
        this.minHeap.add(this.maxHeap.poll());
      }
      if (this.minHeap.size() == this.maxHeap.size() + 2) {
        this.maxHeap.add(this.minHeap.poll());
      }
    }

    public void addNum(int num) {
      if (maxHeap.isEmpty() || num < maxHeap.peek()) {
        maxHeap.add(num);
      } else {
        minHeap.add(num);
      }
      modifyTwoHeapSize();
    }

    public Integer getMedian() {
      int maxHeapSize = this.maxHeap.size();
      int minHeapSize = this.minHeap.size();
      if (maxHeapSize + minHeapSize == 0) {
        return null;
      }
      Integer maxHeapHead = this.maxHeap.peek();
      Integer minHeapHead = this.minHeap.peek();
      if (((maxHeapSize + minHeapSize) & 1) == 0) {
        return (maxHeapHead + minHeapHead) >> 1;
      }
      return maxHeapSize > minHeapSize ? maxHeapHead : minHeapHead;
    }
  }

  public static class MaxHeapComparator implements Comparator<Integer> {
    public int compare(Integer a, Integer b) {
      if (b > a)
        return 1;
      return -1;
    }
  }

  public static class MinHeapComparator implements Comparator<Integer> {
    public int compare(Integer a, Integer b) {
      if (b < a)
        return 1;
      return -1;
    }
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值