Untitled
unknown
c_cpp
3 years ago
2.3 kB
11
Indexable
#include <algorithm>
#include <iostream>
#include <queue>
#include <string>
#include <restbed>
using namespace std;
using namespace restbed;
// MedianFinder class (as defined in previous answer)
class MedianFinder {
public:
// Constructor
MedianFinder() {}
// Add a new number to the stream and update the running median
void addNumber(int num) {
// Add the new number to the appropriate heap
if (maxHeap.empty() || num <= maxHeap.top()) {
maxHeap.push(num);
} else {
minHeap.push(num);
}
// Balance the heaps if necessary
if (maxHeap.size() > minHeap.size() + 1) {
minHeap.push(maxHeap.top());
maxHeap.pop();
} else if (minHeap.size() > maxHeap.size() + 1) {
maxHeap.push(minHeap.top());
minHeap.pop();
}
}
// Return the current median
double getMedian() {
if (maxHeap.size() == minHeap.size()) {
return (maxHeap.top() + minHeap.top()) / 2.0;
} else if (maxHeap.size() > minHeap.size()) {
return maxHeap.top();
} else {
return minHeap.top();
}
}
private:
// Two heaps to store the stream of numbers: a max heap and a min heap
priority_queue<int, vector<int>, less<int>> maxHeap;
priority_queue<int, vector<int>, greater<int>> minHeap;
};
// Global instance of MedianFinder
MedianFinder medianFinder;
// API endpoint for adding a new number to the stream
void addNumber(const shared_ptr<Session> session) {
// Get the request body (a JSON object with a single field "num")
const auto request = session->get_request();
string requestBody = request->get_body();
json requestJson = json::parse(requestBody);
int num = requestJson["num"];
// Add the number to the stream and update the running median
medianFinder.addNumber(num);
// Return the current median in the response
json responseJson;
responseJson["median"] = medianFinder.getMedian();
session->close(OK, responseJson.dump(), { { "Content-Type", "application/json" } });
}
// API endpoint for getting the current median
void getMedian(const shared_ptr<Session> session) {
// Return the current median in the response
json responseJson;
responseJson["median"] = medianFinder.getMedian();
session->close(OK, responseJson.dump(), { { "Content-Type", "application/json" } });
Editor is loading...