80. 中位数(快速排序)

给定一个未排序的整数数组,找到其中位数。

中位数是排序后数组的中间值,如果数组的个数是偶数个,则返回排序后数组的第N/2个数。

样例

给出数组[4, 5, 1, 2, 3], 返回 3

给出数组[7, 9, 4, 5],返回 5

1、选择排序法(时间复杂度高n^2)(一般不选用)

class Solution {
public:
    /*
     * @param : A list of integers
     * @return: An integer denotes the middle number of the array
     */
    int median(vector<int> &nums) {
        // write your code here
        //首先用选择排序法做
        int n=nums.size(),temp;
        for(int i=0;i<n-1;i++)
        { int min=i;
          for(int j=i+1;j<n;j++)
          { if(nums[min]>nums[j])
             min=j;
          }
          if(i!=min)
          {
               temp=nums[i];
               nums[i]=nums[min];
               nums[min]=temp;
              }
        }
         return nums[(n-1)/2];
    }
};

2、快速排序法(推荐)

class Solution {
public:
    /*
     * @param : A list of integers
     * @return: An integer denotes the middle number of the array
     */
    int median(vector<int> &nums) {
        // write your code here
        int n=nums.size()-1;
        Qsort(nums,0,nums.size()-1);
        return nums[n/2];
    }
    
       void Qsort(vector<int> &nums,int low,int high)
    {
        int pivot;
        if(low<high)
        {
            pivot=parition(nums,low,high);
            Qsort(nums,low,pivot-1);
            Qsort(nums,pivot+1,high);
        }
    }
    
    
      int parition(vector<int> &nums,int low,int high)
    {
        int pivotkey,temp;
        pivotkey=nums[low];
        while(low<high)
      {
        while(low<high&&nums[high]>=pivotkey)
         high--;
        
        temp=nums[high];
        nums[high]=nums[low];
        nums[low]=temp;  
        
        while(low<high&&nums[low]<=pivotkey)
            low++;
         
        temp=nums[high];
        nums[high]=nums[low];
        nums[low]=temp;  
      }
      return low;
   }
};

3、利用优先队列

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



  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值