LintCode_中位数
来源:互联网 发布:映客刷人气软件 购买 编辑:程序博客网 时间:2024/06/06 03:02
问题描述:
给定一个未排序的整数数组,找到其中位数。
中位数是排序后数组的中间值,如果数组的个数是偶数个,则返回排序后数组的第N/2个数。
样例:给出数组[4, 5, 1, 2, 3], 返回 3;给出数组[7, 9, 4, 5],返回 5
public static int median(int[] nums){ if(nums==null||nums.length==0){ return 0; } //pos用于表示每一次遍历的起始比较位置 int pos=0; //temp用于保存将要插入的数字 int temp=0; //插入排序法 for(int i=1;i<nums.length;i++){ pos=i-1; temp=nums[i]; while(pos>=0&&temp<nums[pos]){ nums[pos+1]=nums[pos]; pos--; } nums[pos+1]=temp; } //这主要是因为nums的下标是从0开始的 //如果nums长度为偶数,则返回nums.length/2-1处的数字; if(nums.length%2==0){ return nums[nums.length/2-1]; } //如果nums长度为奇数,则返回nums.length/2处的数字; return nums[nums.length/2]; }
0 0
- LintCode_中位数
- 中位数
- 中位数
- 中位数
- 中位数
- 中位数
- 中位数
- 中位数
- 中位数
- 中位数
- 中位数
- 中位数
- 中位数
- 中位数
- 中位数
- 中位数
- 中位数
- 中位数
- android 签名、混淆打包
- 基于用户行为的兴趣标签模型
- django rest framework - 数据解析
- VMWare funtion MAC分辨率自动
- python统一管理多台linux机器
- LintCode_中位数
- 字符串的块链实现
- 飞天马软件下载
- Java编程思想 - 第6章、访问权限控制
- Linux中vi编辑器的使用详解
- 避免Android内存泄露
- StoryBoard不使用AutoLayout情况下 按比例快速兼容适配iPhone6/6 Plus教程【原创】
- 如何用matlab画正态分布曲线
- 两个升序表,打印L中那些由P所指定的位置上的元素 java实现