1. Brute Force — Append & Sort
Intuition
Store all elements in a list. When findMedian() is requested, sort the list in O(N log N) and return the middle element or average of the two middle elements.
When to apply: When total numbers N <= 500 and queries are rare.
Algorithm
- Step 1: addNum(num): push num to list.
- Step 2: findMedian(): sort list ascending.
- Step 3: If list length is odd, return list[n / 2].
- Step 4: If list length is even, return (list[n / 2 - 1] + list[n / 2]) / 2.0.
#include <iostream>#include <vector>#include <algorithm>using namespace std; class MedianFinder { vector<int> nums;public: MedianFinder() {} void addNum(int num) { nums.push_back(num); } double findMedian() { vector<int> sortedNums = nums; sort(sortedNums.begin(), sortedNums.end()); int n = sortedNums.size(); if (n % 2 == 1) { return sortedNums[n / 2]; } return (sortedNums[n / 2 - 1] + sortedNums[n / 2]) / 2.0; }}; int main() { MedianFinder mf; mf.addNum(1); mf.addNum(2); cout << "Median: " << mf.findMedian() << endl; // 1.5 mf.addNum(3); cout << "Median: " << mf.findMedian() << endl; // 2.0 return 0;}Time & Space Complexity
- Time complexity:
addNum: O(1), findMedian: O(N log N)— O(N log N) per median query. - Space complexity:
O(N)— O(N) storage.
Why Brute Force Doesn't Scale:
50,000 insertions into an array take ~1.25 * 109 operations (several seconds). Two-Heaps execute 50,000 insertions in ~8 * 105 operations (15ms).
Two Heaps process 50,000 stream elements in under 20ms.