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解法之外,還可以用優(yōu)先隊列的方式解決,復(fù)雜度為O(n)

最大優(yōu)先隊列的隊首始終為隊列中的最大值,如果需要求中位數(shù),只需要滿足隊列中的所有數(shù)都是較小的數(shù)(小于中位數(shù))即可。

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;
        // 計算出隊列中包括中位數(shù)總共有多少個數(shù)
        int count = (nums.size() + 1) / 2;
        for (int i = 0; i < nums.size(); i++) {
            if (que.size() == count) {
                // 如果隊列中的數(shù)量足夠
                if (que.top() > nums[i]) {
                    // 那么只將較小的數(shù)加入隊列
                    que.pop();
                    que.push(nums[i]);
                }
            } else {
                // 數(shù)量不足時隨便加
                que.push(nums[i]);
            }
        }
        // 最后隊列中全是小于等于中位數(shù)的數(shù),則隊首為中位數(shù)
        return que.top();
    }
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容