[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;
}
}
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 Majority Number iii
- LintCode-最大数
- Subtree
- LintCode --number-of-airplanes-in-the-sky(数飞机)
- LintCode --invert-binary-tree(翻转二叉树)
- LintCode --find-the-missing-number(寻找缺失的数)
- LintCode--best-time-to-buy-and-sell-stock(买卖股票的最佳时机)
- LintCode--best-time-to-buy-and-sell-stock-ii(买卖股票的最佳时机 II)
- 中位数 21% 通过 给定一个未排序的整数数组,找到其中位数。 中位数是排序后数组的中间值,如果数组的个数是偶数个,则返回排序后数组的第N/2个数
- LintCode 翻转二叉树
- LintCode 寻找缺失的数
- LintCode 更新二进制位
- Lintcode 二叉树的后序遍历
- Lintcode 二叉树中序遍历
- Lintcode 二叉树前序遍历
- Lintcode 尾部零的个数
- Lintcode 比较字符串
- Lintcode 主元素
- Lintcode解题笔记 - 岛屿的个数
- LintCode -合并两个排序链表