lintcode 80.Media

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();
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值