C++ | Leetcode C++题解之第295题数据流的中位数

题目:

题解:

cpp 复制代码
class MedianFinder {
    multiset<int> nums;
    multiset<int>::iterator left, right;

public:
    MedianFinder() : left(nums.end()), right(nums.end()) {}

    void addNum(int num) {
        const size_t n = nums.size();

        nums.insert(num);
        if (!n) {
            left = right = nums.begin();
        } else if (n & 1) {
            if (num < *left) {
                left--;
            } else {
                right++;
            }
        } else {
            if (num > *left && num < *right) {
                left++;
                right--;
            } else if (num >= *right) {
                left++;
            } else {
                right--;
                left = right;
            }
        }
    }

    double findMedian() {
        return (*left + *right) / 2.0;
    }
};
相关推荐
云泽80819 小时前
C++ List 容器详解:迭代器失效、排序与高效操作
开发语言·c++·list
xlq2232219 小时前
15.list(上)
数据结构·c++·list
Elias不吃糖20 小时前
总结我的小项目里现在用到的Redis
c++·redis·学习
AA陈超20 小时前
使用UnrealEngine引擎,实现鼠标点击移动
c++·笔记·学习·ue5·虚幻引擎
No0d1es21 小时前
电子学会青少年软件编程(C/C++)六级等级考试真题试卷(2025年9月)
c语言·c++·算法·青少年编程·图形化编程·六级
不会c嘎嘎21 小时前
每日一练 -- day1
c++·算法
yy_xzz21 小时前
VCPKG && Tesseract OCR
c++·图像处理·opencv
hansang_IR1 天前
【记录】网络流最小割建模三题
c++·算法·网络流·最小割
玖笙&1 天前
✨WPF编程进阶【7.3】集成动画(附源码)
c++·c#·wpf·visual studio
Dream it possible!1 天前
LeetCode 面试经典 150_二叉树层次遍历_二叉树的层序遍历(83_102_C++_中等)
c++·leetcode·面试·二叉树