给定一个未排序的整数数组,找到其中位数。
中位数是排序后数组的中间值,如果数组的个数是偶数个,则返回排序后数组的第N/2个数。
样例
给出数组[4, 5, 1, 2, 3], 返回 3
给出数组[7, 9, 4, 5],返回 5
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();
}
};