首页 > 其他分享 >【优先队列】LeetCode 295. 数据流的中位数

【优先队列】LeetCode 295. 数据流的中位数

时间:2023-01-10 14:24:08浏览次数:72  
标签:295 num 中位数 add right 数据流 left LeetCode size

题目链接

295. 数据流的中位数

思路

维护两个优先队列,分别装载排序后数据流左边的数和数据流右边的数,其中 left 为大顶堆,right 为小顶堆。如果元素个数是奇数,则把中位数放到 left 中。

代码

class MedianFinder {
    PriorityQueue<Integer> left = new PriorityQueue<>((a, b) -> b - a);
    PriorityQueue<Integer> right = new PriorityQueue<>((a, b) -> a - b);

    public MedianFinder() {

    }

    public void addNum(int num) {
        if(left.isEmpty()){
            left.add(num);
            return;
        }

        if(num > left.peek()){
            right.add(num);
            while(right.size() > left.size()){
                left.add(right.poll());
            }
        }else{
            left.add(num);
            while(left.size() > right.size() + 1){
                right.add(left.poll());
            }
        }
    }

    public double findMedian() {
        if((left.size() + right.size()) % 2 == 1){
            return 1.0 * left.peek();
        }

        return 1.0 * (left.peek() + right.peek())  / 2.0;
    }
}

标签:295,num,中位数,add,right,数据流,left,LeetCode,size
From: https://www.cnblogs.com/shixuanliu/p/17040176.html

相关文章

  • LeetCode 54_螺旋矩阵
    LeetCode54:螺旋矩阵题目给你一个m行n列的矩阵matrix,请按照顺时针螺旋顺序,返回矩阵中的所有元素。示例1:输入:matrix=[[1,2,3],[4,5,6],[7,8,9]]输出:[1,2,3......
  • [leetcode每日一题]1.9
    ​​1806.还原排列的最少操作步数​​难度中等给你一个偶数 ​​n​​​​​​​,已知存在一个长度为 ​​n​​ 的排列 ​​perm​​ ,其中 ​​perm[i]==i​​(下......
  • 代码随想录算法训练营第八天LeetCode28, 459
    代码随想录算法训练营第八天|LeetCode28,459Leetcode28找出字符串中第一个匹配项的下标题目链接:https://leetcode.cn/problems/find-the-index-of-the-first-occurrence......
  • leetcode-234-easy
    PalindromeLinkedListGiventheheadofasinglylinkedlist,returntrueifitisapalindromeorfalseotherwise.Example1:Input:head=[1,2,2,1]Outpu......
  • leetcode-171-easy
    ExcelSheetColumnNumberGivenastringcolumnTitlethatrepresentsthecolumntitleasappearsinanExcelsheet,returnitscorrespondingcolumnnumber.Fo......
  • leetcode-225-easy
    ImplementStackusingQueuesImplementalast-in-first-out(LIFO)stackusingonlytwoqueues.Theimplementedstackshouldsupportallthefunctionsofanorm......
  • leetcode简单:[1, 9, 13, 14, 20, 21, 26, 27, 35, 58]
    目录1.两数之和9.回文数13.罗马数字转整数14.最长公共前缀20.有效的括号21.合并两个有序链表26.删除有序数组中的重复项27.移除元素35.搜索插入位置58.最后一个......
  • leetcode简单:[66, 67, 70, 83, 121, 141, 160, 169, ,206, 338]
    目录66.加一67.二进制求和70.爬楼梯83.删除排序链表中的重复元素121.买卖股票的最佳时机141.环形链表160.相交链表169.多数元素206.反转链表338.比特位计数66.......
  • LeetCode.977 有序数组的平方
    1.题目给你一个按 非递减顺序 排序的整数数组 ​​​​nums​​​​,返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序。2.代码classSolution{public......
  • LeetCode 46_ 全排列
    LeetCode46:全排列题目给定一个不含重复数字的数组nums,返回其所有可能的全排列。你可以按任意顺序返回答案。示例1:输入:nums=[1,2,3]输出:[[1,2,3],[1,3,2],......