median , not mean, harder

2023-12-15 16:31:08

#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;
}
?

文章来源:https://blog.csdn.net/raidtest/article/details/135019684
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。