zoukankan      html  css  js  c++  java
  • 中位数II

    该题目与思路分析来自九章算法的文章,仅仅是自己做个笔记!

    题目:数字是不断进入数组的,在每次添加一个新的数进入数组的同时返回当前新数组的中位数。

    解答:
    这道题是用堆解决的问题。用两个堆,max heap和min heap,再加一个median值,维持两个堆的大小相等(小根堆可以比大根堆多一个)。对于新来的元素,比较新元素和median的大小,如果小于median就放入大根堆,如果大于median就放入小根堆里面,如果max heap和min heap不平衡了,就调整一下。然后调整过后的median里面的值就是我们要求的中位数。
    参考代码
     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 }
    View Code

    priority_queue<Type, Container, Functional>

     如果我们把后面俩个参数缺省的话,优先队列就是大顶堆,队头元素最大。

    手里拿着一把锤子,看什么都像钉子,编程界的锤子应该就是算法了吧!
  • 相关阅读:
    将博客搬至CSDN
    Fish 下报错 Unsupported use of '||'. In fish, please use 'COMMAND; or COMMAND'.
    使用VMWare虚拟机打开MFC报错:不支持16位系统
    CodeForce Div 2 C. Masha and two friends
    POJ1426 Find The Multiple
    Educational Codeforces Round 54 (Rated for Div. 2) D:Edge Deletion
    CodeForce Educational round Div2 C
    Tenka 1 Computer Contest C-Align
    CodeForce edu round 53 Div 2. D:Berland Fair
    CodeForce 517 Div 2. C Cram Time
  • 原文地址:https://www.cnblogs.com/chess/p/4760327.html
Copyright © 2011-2022 走看看