标签:
该题目与思路分析来自九章算法的文章,仅仅是自己做个笔记!
题目:数字是不断进入数组的,在每次添加一个新的数进入数组的同时返回当前新数组的中位数。
1 #include<iostream> 2 #include<vector> 3 //#include<algorithm> 4 #include<queue> 5 using namespace std; 6 class Solution { 7 public: 8 vector<int> medianII(vector<int>& nums) 9 { 10 vector<int> result; 11 if (nums.size() == 0) 12 return result; 13 int median = nums[0]; 14 priority_queue<int> max_heap, min_heap; 15 result.push_back(median); 16 for (int i = 1; i < nums.size(); ++i)//one by one 17 { 18 if (nums[i] < median) 19 max_heap.push(nums[i]); 20 else 21 min_heap.push(-nums[i]); 22 if (max_heap.size()>min_heap.size()) 23 { 24 min_heap.push(-median); 25 median = max_heap.top(); 26 max_heap.pop(); 27 } 28 else if (max_heap.size() + 1 < min_heap.size()) 29 { 30 max_heap.push(median); 31 median = -min_heap.top(); 32 min_heap.pop(); 33 } 34 result.push_back(median); 35 } 36 return result; 37 } 38 }; 39 int main() 40 { 41 Solution test; 42 vector<int> val = {1,5,6,2,8}; 43 vector<int> res = test.medianII(val); 44 for (auto x : res) 45 cout << x << " "; 46 return 0; 47 }
priority_queue<Type, Container, Functional>
如果我们把后面俩个参数缺省的话,优先队列就是大顶堆,队头元素最大。
标签:
原文地址:http://www.cnblogs.com/chess/p/4760327.html