題目描述:數據結構
Median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value. So the median is the mean of the two middle value.ide
Examples: spa
[2,3,4]
, the median is 3
設計
[2,3]
, the median is (2 + 3) / 2 = 2.5
3d
Design a data structure that supports the following two operations:code
題目分析:blog
題目說的很清楚,須要設計一個數據結構,實現插入以及尋找中位數的功能。感受仍是蠻簡單的,因而很快寫了用vector寫了一個。結果OJ顯示超時了,看了一下超時的樣例,太變態了,一直在插入,尋找......超時緣由就是,頻繁的插入,使得vector一直在從新分配內存,並且屢次所有進行排序成本過高。排序
1 class MedianFinder { 2 public: 3 std::vector<int> m_num; 4 // Adds a number into the data structure. 5 void addNum(int num) { 6 m_num.push_back(num); 7 } 8 9 // Returns the median of current data stream 10 double findMedian() { 11 sort(m_num.begin(),m_num.end()); 12 int n = m_num.size(); 13 return (m_num[n/2] + m_num[(n-1)/2])/2; 14 } 15 }; 16 17 // Your MedianFinder object will be instantiated and called as such: 18 // MedianFinder mf; 19 // mf.addNum(1); 20 // mf.findMedian();
考慮使用其餘的數據結構。嘗試一下STL中自帶可排序的數據結構set,set中不能出現重複元素,考慮使用multi_set。並且題目中只關心中間的兩個數,能夠用兩個multiset分別存放較小的部分和較大的部分,只要保證兩邊的容量保持平衡便可。提交以後,能夠AC。除了set以外還能夠考慮使用,優先隊列,只要能夠進行排序的stl容器均可以成功實現這個功能。隊列
class MedianFinder { public: std::multiset<int> m_left; std::multiset<int> m_right; // Adds a number into the data structure. void addNum(int num) { if (m_left.size() == m_right.size()) //判斷兩邊容量大小 { if (m_right.size()&&num > *m_right.begin()) //若是右邊不爲空,且新插入的值比右邊最小值大,進行調整 { //將右邊的最小值放入左邊,新值插入右邊 m_right.insert(num); int temp = *m_right.begin(); m_left.insert(temp); m_right.erase(m_right.begin()); } else m_left.insert(num); } else { if (num < *m_left.rbegin()) //一樣進行判斷,若是比左邊最大值小,插入左邊,進行調整 { m_left.insert(num); int temp = *m_left.rbegin(); m_right.insert(temp); m_left.erase(--m_left.end()); } else m_right.insert(num); } } // Returns the median of current data stream double findMedian() { return m_left.size()==m_right.size()?(*m_left.rbegin() + *m_right.begin())/(double)2:*m_left.rbegin(); } };