您的位置:首页 > 产品设计 > UI/UE

[LintCode]Find Median of Unsorted Array O(n) quick sort

2015-11-07 11:02 543 查看


Easy Median
Show result 

21%

Accepted

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.
记忆中做过这个题目,找不到了。这次做遇到一个bug,做了很久。这个做法作为一个quick sort 的standard。 已末尾元素为pivot
另外,我一律用的是绝对坐标纪录起始与目标 位置,最后要找的位置,也是坐标。比起来找一个size, 绝对坐标是不变的, 更方便, 不需要在右半边情况时候,重新计算size了。

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 helper(nums, 0, nums.length-1, (nums.length-1)/2 );
}
public int helper(int[] nums, int s, int e, int targetIndex){
int pivot = nums[e];
//quick sort
int r = e-1, l = s;
while(l <= r){
if(nums[l] > pivot){
swap(nums, l, r);
r--,l--;
}
l++;
}
swap(nums, l, e);

if(l == targetIndex){
return nums[l];
}else if(l > targetIndex){
return helper(nums, s, l-1, targetIndex );
}else{
return helper(nums, l+1, e, targetIndex );
}
}

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