leetcode中两道关于中位数的题295和480

本文探讨了LeetCode上的第295和480题,这两道题目都涉及到寻找中位数。解题策略是利用两个堆,一个为最小堆,另一个为最大堆,以此来动态维护数列的中位数。
摘要由CSDN通过智能技术生成

两道题的思路是一样的,都是建立2个堆,一个是最小堆,一个是最大堆

295题

/*
 * Design a data structure that supports the following two operations:

void addNum(int num) - Add a integer number from the data stream to the data structure.
double findMedian() - Return the median of all elements so far.
 * */
import java.util.Comparator;
import java.util.PriorityQueue;


//方法类似与480题的sliding window median
 /*
     Use two Heaps to store numbers. maxHeap for numbers smaller than current
	 * median, minHeap for numbers bigger than and equal to current median. A
	 * small trick I used is always make size of minHeap equal (when there are
	 * even numbers) or 1 element more (when there are odd numbers) than the
	 * size of maxHeap
	*/
public class MedianFinder {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		MedianFinder mf = new MedianFinder();
		mf.addNum(1);
		mf.addNum(2);
		System.out.println(mf.findMedian());
		mf.addNum(3);
		System.out.println(mf.findMedian());
	}

	PriorityQueue<Integer> minHeap;//使minHeap中的个数等于或者比maxHeap多1,这样对于返回中位数操作就相对简单
	PriorityQueue<Integer> maxHeap;

	public MedianFinder() {
		this.minHeap = new PriorityQueue<>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值