描述
给定一个未排序的整数数组,找到其中位数。
中位数是排序后数组的中间值,如果数组的个数是偶数个,则返回排序后数组的第N/2个数。
您在真实的面试中是否遇到过这个题?
是
样例
给出数组[4, 5, 1, 2, 3], 返回 3
给出数组[7, 9, 4, 5],返回 5
挑战
时间复杂度为O(n)
这是一个以空间换取时间的做法:
建立散列表,值与个数一一对应,记录最大值与最小值,统计数组个数,找出中位数所在的位置。从一边开始遍历,记录个数。直到中位数的位置,然后返回中位数。
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 map<int,int> vis; int count; int minp=nums[0]; int maxp=nums[0]; for(auto e:nums){ ++vis[e]; minp=min(e,minp); maxp=max(e,maxp); } int n=nums.size(); count=(n&1)?n/2+1:n/2; for(int i=minp;i<=maxp;++i){ while(vis[i]>0){ --vis[i],--count; if(count==0) return i; } } } };