1. 程式人生 > 實用技巧 >Leetcode刷題 - 在資料流找中位數(Find Median from Data Stream)

Leetcode刷題 - 在資料流找中位數(Find Median from Data Stream)

方法一:Insertion Sort

 1 class MedianFinder {
 2     vector<int> store; // resize-able 
 3 public:
 4     /** initialize your data structure here. */
 5     MedianFinder() {
 6         
 7     }
 8     
 9     void addNum(int num) {
10         if (store.empty())
11             store.push_back(num);
12
else 13 // insert(position, value) 14 // lower_bound(interator first, interator last, num) -> return 15 // return 在range裡第一個小於這個num的位置 16 // binary search combined with insertion 17 store.insert(lower_bound(store.begin(), store.end(), num), num);
18 } 19 20 double findMedian() { 21 int n = store.size(); 22 //利用二進位制快速判斷奇偶數 23 return n & 1 ? store[n/2] : ((double) store[n/2 - 1] + store[n/2])*0.5; 24 } 25 };

方法二:Two Heap

 1 class MedianFinder{
 2     //優先佇列建立最大堆
 3     priority_queue<int> lo; // max heap
4 // 優先佇列建立最小堆 5 priority_queue<int, vector<int>, greater<int>> hi; // min heap 6 public: 7 void addNum(int num){ 8 // Add to max heap 9 lo.push(num); 10 // balance step 11 hi.push(lo.top()); 12 13 lo.pop(); 14 15 // maintain size property 16 if(lo.size() < hi.size()){ 17 lo.push(hi.top()); 18 hi.pop(); 19 } 20 } 21 22 double findMedian(){ 23 return lo.size() > hi.size() ? lo.top() : ((double) lo.top() + hi.top())*0.5; 24 } 25 };