本文将对这个问题进行深入分析。
正常数据量,O(n)的方法
http://www.lintcode.com/en/problem/median
可以用类似快排的方法以
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) {
// write your code here
if (nums == null) {
return -1;
}
int k = (nums.length + 1) / 2;
int result = findKth(nums, k);
return result;
}
public int partition(int[] nums, int start, int end) {
int i = start;
int j = end;
int pivotValue = nums[i];
while(i < j) {
while(i < j && nums[j] >= pivotValue) {
j--;
}
nums[i] = nums[j];
while(i < j && nums[i] < pivotValue) {
i++;
}
nums[j] = nums[i];
if (i == j) {
nums[i] = pivotValue;
return i;
}
}
return i;
}
public int helper(int[] nums, int start, int end, int k) {
int loc = partition(nums, start, end);
if (loc == k) {
return nums[loc];
} else if (loc < k) {
return helper(nums, loc + 1, end, k);
} else {
return helper(nums, start, loc - 1, k);
}
}
public int findKth(int[] nums, int k) {
return helper(nums, 0, nums.length - 1, k - 1);
}
}
大数据量,单机怎么做
- 使用外部归并排序
怎么用堆做?用Java的PriorityQueue实现?