查找众数及中位数
题目描述:
1.众数是指一组数据中出现次数量多的那个数,众数可以是多个
2.中位数是指把一组数据从小到大排列,最中间的那个数,如果这组数据的个数是奇数,那最中间那个就是中位数,
如果这组数据的个数为偶数,那就把中间的两个数之和除以 2,所得的结果就是中位数
3.查找整型数组中元素的众数并组成一个新的数组,求新数组的中位数
输入描述:
输入一个一维整型数组,数组大小取值范围 0 < N < 1000,数组中每个元素取值范围 0 < E < 1000
输出描述:
输出众数组成的新数组的中位数
示例 1:
输入
10 11 21 19 21 17 21 16 21 18 15
输出
21
#include<iostream>
#include<vector>
#include<algorithm>
#include<unordered_map>
using namespace std;
int main(){
int input;
vector<int> v;
vector<int> new_v;
unordered_map<int,int> vnums;
int cnt=0;
while(cin>>input){ //这里需要输入一个非int类型来跳出输入循环
v.push_back(input);
}
for(auto i:v){
vnums[i]++;
}
for(auto i:vnums){
if(cnt<i.second){
cnt=i.second;
}
}
for(auto i:vnums){
if(i.second==cnt){
new_v.push_back(i.first);
}
}
sort(new_v.begin(),new_v.end());
if(new_v.size()!=0 && new_v.size()%2==0){
cout<<(new_v[new_v.size()/2]+new_v[new_v.size()/2-1])/2;
}
else if(new_v.size()%2!=0){
cout<<new_v[new_v.size()/2];
}
else {
cout<<endl;
}
return 0;
}