博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Median
阅读量:4577 次
发布时间:2019-06-08

本文共 2071 字,大约阅读时间需要 6 分钟。

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

你可能感兴趣的文章
怎么让table中的<td>内容向上对齐
查看>>
[Java] 遍历HashMap和HashMap转换成List的两种方式
查看>>
mongodb
查看>>
LeetCode 46. Permutations
查看>>
jmeter- 性能测试3:聚合报告(Aggregate Report )
查看>>
JavaScript高级程序设计---学习笔记(二)
查看>>
vim 插件的学习
查看>>
Uncaught SyntaxError: Unexpected token ILLEGAL
查看>>
一个预处理定义的问题
查看>>
神经网路-SGD-1
查看>>
安卓冷知识:LayoutParams
查看>>
JAVA操作mysql(如何更加面向对象的操作数据库)
查看>>
Python9-事件及队列-day37
查看>>
ANDROID L——Material Design综合应用(Demo)
查看>>
django使用户名和邮箱都能登录
查看>>
Java是否可用public成员变量?
查看>>
DNS解析原理和流程
查看>>
【rust】-使用cargo创建项目及cargo源的替换
查看>>
自我介绍以及关于软件工程的问题
查看>>
struts (一)
查看>>