Lintcode: Median

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.

Quicksort的变形,quickselect,跟Kth largest Element很像

 1 public class Solution {
 2     /**
 3      * @param nums: A list of integers.
 4      * @return: An integer denotes the middle number of the array.
 5      */
 6     public int median(int[] nums) {
 7         // write your code here
 8         int len  = nums.length;
 9         if (len%2 == 0) return search(nums, len/2, 0, len-1);
10         else return search(nums, len/2+1, 0, len-1);
11     }
12     
13     public int search(int[] nums, int k, int start, int end) {
14         int l=start, r=end;
15         int pivot = r;
16         while (true) {
17             while (nums[l] < nums[pivot] && l<r) {
18                 l++;
19             }
20             while (nums[r] >= nums[pivot] && l<r) {
21                 r--;
22             }
23             if (l == r) break;
24             swap(nums, l, r);
25         }
26         swap(nums, l, end);
27         if (k == l+1) return nums[l];
28         else if (k > l+1) return search(nums, k, l+1, end);
29         else return search(nums, k, start, l-1);
30     }
31     
32     public void swap(int[] nums, int l, int r) {
33         int temp = nums[l];
34         nums[l] = nums[r];
35         nums[r] = temp;
36     }
37 }

 

转载于:https://www.cnblogs.com/EdwardLiu/p/4340933.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值