80. 中位数
给定一个未排序的整数数组,找到其中位数。
中位数是排序后数组的中间值,如果数组的个数是偶数个,则返回排序后数组的第N/2个数。
样例
样例 1:
输入:[4, 5, 1, 2, 3]
输出:3
解释:
经过排序,得到数组[1,2,3,4,5],中间数字为3
样例 2:
输入:[7, 9, 4, 5]
输出:5
解释:
经过排序,得到数组[4,5,7,9],第二个(4/2)数字为5
挑战
时间复杂度为O(n)
注意事项
数组大小不超过10000
public class Solution {
/**
* @param nums: A list of integers
* @return: An integer denotes the middle number of the array
*/
public int median(int[] nums) {
// write your code here
return midian(nums,0,nums.length-1,(nums.length+1)/2-1);
}
public int midian(int[] a,int left,int right,int target) {
// write your code here
if(left < right) {
int i = left;
int j = right;
int x = a[left];
while(i < j ) {
while(i < j && a[j] >= x)
j--;
if(i<j) {
a[i]=a[j];
i++;
}
while(i < j && a[i] <= x)
i++;
if(i<j) {
a[j]=a[i];
j--;
}
}
a[i] = x;
if(i == target)
return a[i];
if(i > target) {
return midian(a,left,i-1,target);
}
if(i<target) {
return midian(a,i+1,right,target);
}
}
return a[left];
}
}