[LintCode]Find Median of Unsorted Array O(n) quick sort
2015-11-07 11:02
543 查看
Easy Median
Show result
21%Accepted
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.
记忆中做过这个题目,找不到了。这次做遇到一个bug,做了很久。这个做法作为一个quick sort 的standard。 已末尾元素为pivot
另外,我一律用的是绝对坐标纪录起始与目标 位置,最后要找的位置,也是坐标。比起来找一个size, 绝对坐标是不变的, 更方便, 不需要在右半边情况时候,重新计算size了。
public class Solution { /** * @param nums: A list of integers. * @return: An integer denotes the middle number of the array. */ public int median(int[] nums) { // write your code here return helper(nums, 0, nums.length-1, (nums.length-1)/2 ); } public int helper(int[] nums, int s, int e, int targetIndex){ int pivot = nums[e]; //quick sort int r = e-1, l = s; while(l <= r){ if(nums[l] > pivot){ swap(nums, l, r); r--,l--; } l++; } swap(nums, l, e); if(l == targetIndex){ return nums[l]; }else if(l > targetIndex){ return helper(nums, s, l-1, targetIndex ); }else{ return helper(nums, l+1, e, targetIndex ); } } public void swap(int[] nums, int i, int j){ int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } }
相关文章推荐
- Longest Consecutive Sequence 解答
- play2.0 集成 squeryl
- 触摸事件UITouch的用法
- UIButton内部子控件自定义布局-“UIEdgeInsets”
- 4.Arduino IDE代码如下
- UIBarButtonItemSystemItemFixedItem设定指定宽度的barButtonItem
- hdoj 2767 Proving Equivalences【强连通&&tarjan】
- IOS UISegmentedControl 分段控制器
- UIScrollView的代理(delegate)
- UIScrollView作为第一个初始化View,导致其内的第一个UIimageView只显示一半的高度
- codeforces-446A-DZY Loves Sequences
- explaining of genotyping and DNA resequencing and variant calling
- SQL Interview Question
- 使用代码提示miui系统开启悬浮框
- Codeforces Round #328 (Div. 2)B. The Monster and the Squirrel
- uinavigationBar常用设置
- UISearchBar custom
- ExecuteThread: '33' for queue: 'weblogic.kernel.Default (self-tuning)'] ERROR
- iOS开发:UIImage赋颜色-----给image赋16进制颜色值
- LightOJ - 1081 Square Queries(二维RMQ)