原題
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();
}
};