80. Median
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
Example 1:
Input:[4, 5, 1, 2, 3]
Output:3
Explanation:
After sorting,[1,2,3,4,5],the middle number is 3
Example 2:
Input:[7, 9, 4, 5]
Output:5
Explanation:
After sorting,[4,5,7,9],the second(4/2) number is 5
Challenge
O(n) time.
Notice
The size of array is not exceed 10000
Input test data (one paramete
思路
看网上很多人用的快排思想,但是我数据局结构还没复习。。。发现用优先队列做很巧妙了!!!
优先队列在队首总是最大的那个数字。
解答
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
int k = (nums.size()+1)/2;
priority_queue<int> que;
int len = nums.size();
for(int i=0; i<len; i++){
if(que.size()==k){
if(nums[i] < que.top()){
que.pop();
que.push(nums[i]);
}
}else{
que.push(nums[i]);
}
}
return que.top();
}
};