LintCode80
来源:互联网 发布:win7桌面时钟软件 编辑:程序博客网 时间:2024/06/05 11:30
给定一个未排序的整数数组,找到其中位数。
中位数是排序后数组的中间值,如果数组的个数是偶数个,则返回排序后数组的第N/2个数。
给出数组[4, 5, 1, 2, 3], 返回 3
给出数组[7, 9, 4, 5],返回 5
代码:
class Solution {
public:
/**
* @param nums: A list of integers.
* @return: An integer denotes the middle number of the array.
*/
void quicksort(vector<int> &a, int low, int high)
{
if (low >= high)
return;
int i = low;
int j = high;
int key = a[i];
while (i < j)
{
while (i < j && a[j] >= key)//找比key小的
j--;
a[i] = a[j];
while (i < j && a[i] <= key)//找比key大的
i++;
a[j] = a[i];
}
//循环结束,i==j
a[i] = key;/*pivot入位*/
quicksort(a, low, i - 1);
quicksort(a, i + 1, high);
}
int median(vector<int> &nums) {
quicksort(nums,0,nums.size()-1);
if(nums.size()%1)
return nums[nums.size()/2];
else
return nums[(nums.size()-1)/2];
// write your code here
}
};
- LintCode80
- LintCode80:中位数
- HDU6071Lazy Running(同余最短路)
- 简单使用Axure 模拟Android中的fragment切换
- Computer and Computer Science
- JavaScript闭包
- Android TV蓝牙模块
- LintCode80
- bson对象的解析
- POJ3279 Fliptile
- JVM学习笔记(9)-性能监控
- 动态绑定和静态绑定
- cannot find a valid baseurl for repo
- 从代码上看Zookeeper Client如何建立与保持服务端的连接
- 单脉冲发生器设计
- selenium初学(一)浏览器篇