median , not mean, harder

#include <iostream>
#include <queue>

class RealTimeMedianCalculator {
private:
    std::priority_queue<int> maxHeap; // Stores the smaller half of the numbers
    std::priority_queue<int, std::vector<int>, std::greater<int>> minHeap; // Stores the larger half of the numbers

public:
    void processInput(int number) {
        if (maxHeap.empty() || number <= maxHeap.top()) {
            maxHeap.push(number);
        } else {
            minHeap.push(number);
        }

        // Balance the heaps
        if (maxHeap.size() > minHeap.size() + 1) {
            minHeap.push(maxHeap.top());
            maxHeap.pop();
        } else if (minHeap.size() > maxHeap.size()) {
            maxHeap.push(minHeap.top());
            minHeap.pop();
        }

        double median;
        if (maxHeap.size() == minHeap.size()) {
            median = (static_cast<double>(maxHeap.top()) + minHeap.top()) / 2.0;
        } else {
            median = static_cast<double>(maxHeap.top());
        }

        std::cout << "Median up to now: " << median << std::endl;
    }
};

int main() {
    RealTimeMedianCalculator calculator;

    std::cout << "Enter integers (type 'exit' to stop):" << std::endl;

    while (true) {
        std::string input;
        std::cin >> input;

        if (input == "exit") {
            break;
        }

        try {
            int number = std::stoi(input);
            calculator.processInput(number);
        } catch (const std::invalid_argument& e) {
            std::cout << "Invalid input. Please enter an integer or type 'exit' to stop." << std::endl;
        }
    }

    return 0;
}
// Memory space savior :

#include <iostream>
#include <tdigest/TDigest.h> //this is the key https://github.com/derrickburns/tdigest/blob/master/TDigest.h

int main() {
    TDigest digest;
    double number;
    // Read numbers from stdin until EOF
    while (std::cin >> number) {
        digest.add(number);
        std::cout << "The estimated median of all numbers to now is: " << digest.percentile(50) << '\n';
    }
    return 0;
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值