Source
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
Challenge
O(n) time.
Java
public class Solution {
public int median(int[] nums) {
int k = nums.length/2 + 1;
return quickSelect(nums, 0, nums.length - 1, k);
}
private int quickSelect(int[] nums, int start, int end, int k) {
int pivot = end;
int left = start;
int right = end - 1;
while (left <= right) {
if (nums[left] > nums[pivot]) {
swap(nums, left, right);
right--;
} else {
left++;
}
}
swap(nums, left, pivot);
int rank = nums.length - left;
if (rank == k) return nums[left];
if (rank > k) return quickSelect(nums, left + 1, end, k);
return quickSelect(nums, start, left - 1, k);
}
private void swap(int[] nums, int a, int b) {
int tmp = nums[a];
nums[a] = nums[b];
nums[b] = tmp;
}
}