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
.
第一种方法:
直接先排序后取中位数,思路很简单,但是时间复杂度稍高。
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 n = nums.size();
sort(nums.begin(),nums.end());
return nums[(n-1)/2];
}
};
第二种方法:
利用快速排序的特性,由于每次快排partition操作后,总有一个元素被放置在排好序后的正确位置p,通过检测这个元素是否为中位数(p == nums.size()-1/2),若是直接返回,若不是则在中位数本应该在的区间继续进行快排,直到找到这个中位数。这样就只是对少量元素进行排序就找到了中位数,不需要全部遍历。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
return quickSort(nums, 0, nums.size()-1);
}
int partition(vector<int> &nums, int l, int r)//返回p,使得nums[l...p-l] < nums[p] ; nums[p+1...r] > nums[p]
{
int v = nums[l];
int j = l;
int i = j + 1;
for (; i <= r; i++)
{
if (nums[i] < v)
{
swap(nums[j+1], nums[i]);
j++;
}
}
swap(nums[l], nums[j]);
return j;
}
int quickSort(vector<int> &nums, int l, int r)//对nums[l...r]部分进行快速排序
{
int p = partition(nums, l, r);
if (p == (nums.size() - 1) / 2)
return nums[p];
else if(p > (nums.size() - 1) / 2)
quickSort(nums, l, p - 1);
else
quickSort(nums, p+1, r);
}
};