题目:中位数
问题描述:
给定一个未排序的整数数组,找到其中位数。
中位数是排序后数组的中间值,如果数组的个数是偶数个,则返回排序后数组的第N/2个数。
样例
给出数组[4, 5, 1, 2, 3], 返回 3
给出数组[7, 9, 4, 5],返回 5
思路:先用sort函数把数组排好序,再计算出该数组有多少个整数,然后算出中位数所处的位置,返回该位置的整数。注意,位置是从0开始的。
代码:
class Solution {
public:
/**
* @param nums: A list of integers.
* @return: An integer denotes the middle number of the array.
*/
int median(vector<int> &nums) {
// write your code here
sort(nums.begin(),nums.end());
int i,k,v;
int count=nums.size();
if(count%2==0) k=count/2;
else k=(count+1)/2;
return nums[k-1];
}
};
感想:一定要注意审题,刚开始没审好题就做,理所当然地认为中位数是数学上学的中位数了,错了好几次,幸好有好多次机会,要不这道题一分没有。