LintCode 80. Median

原题

LintCode 80. Median

Description

Given a unsorted array with integers, find the median of it.
A median is the middle number of the array after it is sorted.
If there are even numbers in the array, return the N/2-th number after sorted.

Example

Given [4, 5, 1, 2, 3], return 3.

Given [7, 9, 4, 5], return 5.

解题

除了排序这种Naive解法之外,还可以用优先队列的方式解决,复杂度为O(n)

最大优先队列的队首始终为队列中的最大值,如果需要求中位数,只需要满足队列中的所有数都是较小的数(小于中位数)即可。

class Solution {
public:
    /**
    * @param nums: A list of integers.
    * @return: An integer denotes the middle number of the array.
    */
    int median(vector<int> &nums) {
        // write your code here
        priority_queue<int> que;
        // 计算出队列中包括中位数总共有多少个数
        int count = (nums.size() + 1) / 2;
        for (int i = 0; i < nums.size(); i++) {
            if (que.size() == count) {
                // 如果队列中的数量足够
                if (que.top() > nums[i]) {
                    // 那么只将较小的数加入队列
                    que.pop();
                    que.push(nums[i]);
                }
            } else {
                // 数量不足时随便加
                que.push(nums[i]);
            }
        }
        // 最后队列中全是小于等于中位数的数,则队首为中位数
        return que.top();
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,768评论 0 33
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,811评论 0 23
  • 我们穿越山海去寻找寄托 在最古老的森林找回晨曦的美丽 我早已忘记 忘记我的出生 我的名字 我还跟这个世界有什么联系...
    辛亿阅读 389评论 0 0
  • 2016年9月26日14:50李小妞出生啦,2.45公斤,小不点一枚!由于羊水少,李小妞出生后也是受了点小...
    李洁玉阅读 259评论 0 0
  • 我是一个码农。 关注公众号:码农和果园
    码农果园阅读 1,025评论 2 5