80.Median-中位数(容易题)
来源:互联网 发布:iface302 指纹算法 编辑:程序博客网 时间:2024/06/04 18:28
中位数
题目
给定一个未排序的整数数组,找到其中位数。
中位数是排序后数组的中间值,如果数组的个数是偶数个,则返回排序后数组的第N/2个数。
样例
给出数组[4, 5, 1, 2, 3], 返回 3
给出数组[7, 9, 4, 5],返回 5
挑战
时间复杂度为O(n)
题解
1.Hashmap法,以空间换时间,时间复杂度为O(n)
先通过一次遍历得到最大值和最小值,并把元素值作为Hashmap的K、把元素出现的次数作为V。
需要注意的是中位数出现的位置应该是:
int count = n % 2 == 1 ? n / 2 + 1 : n / 2;
然后从最小值到最大值对Hashmap进行遍历,每找到一个元素就将count值减1(可以解释为什么count的下标为1而不是0),当count==0时Hashmap的K即是答案。
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 min = nums[0]; int max = nums[0]; int n = nums.length; HashMap<Integer,Integer> hashmap = new HashMap<>(); for (int i=0;i<n;i++) { int value = hashmap.containsKey(nums[i]) ? hashmap.get(nums[i])+1 : 1; hashmap.put(nums[i],value); min = min < nums[i] ? min : nums[i]; max = max > nums[i] ? max : nums[i]; } int count = n % 2 == 1 ? n / 2 + 1 : n / 2; for (int i = min;i<=max;i++) { while (hashmap.containsKey(i) && hashmap.get(i)>0) { --count; hashmap.put(i,hashmap.get(i)-1); if (count == 0) { return i; } } } return Integer.MAX_VALUE;//表示出错 }}
2.Top K方法
本题的实质是查找数组中第(n-1)/2大的数,属于Top K问题,即使用快排思想解决问题,时间复杂度是O(n)。
public class Solution { /** * @param nums: A list of integers. * @return: An integer denotes the middle number of the array. */ public int median(int[] nums) { return getMinK(nums,0,nums.length-1,(nums.length-1)/2); } private int getMinK(int[] nums, int left, int right, int k) { int i = left; int j = right; while (i != j) { while (nums[j] >= nums[left] && i < j) { j--; } while (nums[i] <= nums[left] && i < j) { i++; } swap(nums,i,j); } swap(nums,left,i); if (i == k) { return nums[i]; } else if (i < k) { return getMinK(nums,i+1,right,k); } else { return getMinK(nums,left,i-1,k); } } private void swap(int[] nums, int i, int j) { int tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; }}
Last Update 2016.8.31
0 0
- 80.Median-中位数(容易题)
- 【枚举】中位数(median)
- 中位数(Median)
- median of medians(中位数的中位数)
- HackerRank Find Median(中位数)
- SGU - 358 - Median of Medians (寻找中位数中的中位数)
- 中位数(又称中值,英语:Median)
- PAT 1029 Median(中位数+归并排序)
- OJ_1004 Median 求中位数
- 【算法】中位数 median
- HDU3194 Median【中位数+排序】
- MDX示例:求解中位数、四分位数(median、quartile)
- LeetCode 295. Find Median from Data Stream(数据流中位数)
- LeetCode | 4. Median of Two Sorted Arrays(中位数)
- 九度:1004<Median><中位数>
- codeforces 166C Median 中位数
- POJ2623 Sequence Median【中位数+排序】
- POJ_Dynamic Median 数据流的中位数
- Thread.currentThread().getContextClassLoader() 和 Class.getClassLoader()区别
- ArcGIS空间插值方法反距离权重法(IDW)的工作原理
- JSP page指令
- Android布局管理之LinearLayout
- 自学之路
- 80.Median-中位数(容易题)
- 自媒体人不做广告怎么吃饭
- MyEClipse环境配置(详解)
- 文本输入与输出(2)
- 根据选中的单选按钮获取值
- ActiveMQ持久化消息的三种方式
- MySQL comment
- redis 学习指南
- X,Y,frame,size重写为UIView创建分类