[CareerCup] 18.9 Find and Maintain the Median Value 寻找和维护中位数
生活随笔
收集整理的這篇文章主要介紹了
[CareerCup] 18.9 Find and Maintain the Median Value 寻找和维护中位数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
18.9 Numbers are randomly generated and passed to a method. Write a program to find and maintain the median value as new values are generated.
?
LeetCode上的原題,請參見我之前的博客Find Median from Data Stream.
?
解法一:
priority_queue<int> small; priority_queue<int, vector<int>, greater<int>> large;void addNum(int num) {small.push(num);large.push(small.top());small.pop();if (small.size() < large.size()) {small.push(large.top());large.pop();} }double find_median() {return small.size() > large.size() ? small.top() : 0.5 * (small.top() + large.top()); }?
解法二:
priority_queue<int> small, large;void addNum(int num) {small.push(num);large.push(-small.top());small.pop();if (small.size() < large.size()) {small.push(-large.top());large.pop();} }double find_median() {return small.size() > large.size() ? small.top() : 0.5 * (small.top() - large.top()); }?
CareerCup All in One 題目匯總
?
總結
以上是生活随笔為你收集整理的[CareerCup] 18.9 Find and Maintain the Median Value 寻找和维护中位数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python脚本备份数据库
- 下一篇: CSharpGL(23)用Compute