描述
給定一個(gè)未排序的整數(shù)數(shù)組,找到其中位數(shù)。
中位數(shù)是排序后數(shù)組的中間值,如果數(shù)組的個(gè)數(shù)是偶數(shù)個(gè)脸秽,則返回排序后數(shù)組的第N/2個(gè)數(shù)。
樣例
給出數(shù)組[4, 5, 1, 2, 3]蝴乔, 返回 3
給出數(shù)組[7, 9, 4, 5]记餐,返回 5
挑戰(zhàn)
時(shí)間復(fù)雜度為O(n)
代碼
public class Solution {
/*
* @param nums: A list of integers
* @return: An integer denotes the middle number of the array
*/
public int median(int[] nums) {
if (nums == null) {
return - 1;
}
return quickSelect(nums, 0, nums.length - 1, (nums.length + 1) / 2);
}
private int quickSelect(int[] nums, int start, int end, int k) {
if (start >= end) {
return nums[start];
}
int left = start;
int right = end;
int pivot = nums[start + (end - start) / 2];
while (left <= right) {
while (left <= right && nums[left] < pivot) {
left++;
}
while (left <= right && nums[right] > pivot) {
right--;
}
if (left <= right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
left++;
right--;
}
}
if (start + k - 1 <= right) {
return quickSelect(nums, start, right, k);
}
if (start + k - 1 >= left) {
return quickSelect(nums, left, end, k - (left - start));
}
return pivot;
}
}