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.

思路:1.排序,找到其Median,时间复杂度为 O(nlogn).

   2.找从小到大的第K个数,找median则转换为找从小到大的 nums.length / 2 (当 nums.length 为偶数时) 或 nums.length / 2 + 1 (当nums.length 为奇数时). 时间复杂度为O(n).

       找从小到大第K个数的关键是 快速排序的核心 partition.

相关题目:Kth Largest Element in an Array (从大到小的第K个数)

 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         if (nums == null || nums.length == 0) {
 8             return -1;
 9         }
10         if (nums.length % 2 == 0) {
11             return findKth(nums, 0, nums.length - 1, nums.length / 2);
12         } else {
13             return findKth(nums, 0, nums.length - 1, nums.length / 2 + 1);
14         }
15         
16     }
17     
18     private int findKth(int[] nums, int left, int right, int k) {
19         if (left == right) {
20             return nums[left];
21         }
22         int position = partition(nums, left, right);
23         if (position + 1 == k) {
24             return nums[position];
25         } else if (position + 1 > k) {
26             return findKth(nums, left, position - 1, k);
27         } else {
28             return findKth(nums, position + 1, right, k);
29         }
30     }
31     
32     private int partition(int[] nums, int left, int right) {
33         int pivote = nums[left];
34         while (left < right) {
35             while (left < right && nums[right] >= pivote) {
36                 --right;
37             }
38             nums[left] = nums[right];
39             while (left < right && nums[left] <= pivote) {
40                 ++left;
41             }
42             nums[right] = nums[left];
43         }
44         nums[left] = pivote;
45         return left;
46     }
47 }

 

转载于:https://www.cnblogs.com/FLAGyuri/p/5436432.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值