您的位置:首页 > 其它

[Lintcode]Median

2016-02-21 18:49 302 查看
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.

要求O(n)时间复杂度.

与快速排序同理。平均复杂度满足题目要求。left左侧为比pivot小的数字。当left=pivot时,同时满足1)排序数组 2)第mid个数字

public class Solution {
/**
* @param nums: A list of integers.
* @return: An integer denotes the middle number of the array.
*/
public int median(int[] nums) {
int mid = nums.length % 2 == 0 ? (nums.length - 1) / 2 : nums.length / 2;
return helper(nums, 0, nums.length - 1, mid);
}

private int helper(int[] nums, int start, int end, int mid) {
int pivot = nums[end];
int left = start, right = end;
while(left < right) {
while(left < right && nums[left] < pivot) {
left ++;
}
while(left < right && nums[right] >= pivot) {
right --;
}
swap(nums, left, right);
}
swap(nums, left, end);

if(left == mid) return nums[left];
else if(left < mid) return helper(nums, left + 1, end, mid);
else return helper(nums, start, end - 1, mid);
}

void swap(int[] num, int left, int right) {
int tmp = num[left];
num[left] = num[right];
num[right] = tmp;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  lintcode