0034-求众数中的中位数
题目描述
1.众数是指一组数据中出现次数多的数
众数可以是多个
2.中位数是指把一组数据从小到大排列,最中间的那个数,
如果这组数据的个数是奇数,那最中间那个就是中位数
如果这组数据的个数为偶数,那就把中间的两个数之和除以2就是中位数
3.查找整型数组中元素的众数并组成一个新的数组
求新数组的中位数
输入描述
输入一个一维整型数组,数组大小取值范围 0<n<1000
数组中每个元素取值范围, 0<e<1000
输出描述
输出众数组成的新数组的中位数
输出输出样例
示例一
输入:
10 11 21 19 21 17 21 16 21 18 16
输出
21
示例二
输入
2 1 5 4 3 3 9 2 7 4 6 2 15 4 2 4
输出
3
示例三
输入
5 1 5 3 5 2 5 5 7 6 7 3 7 11 7 55 7 9 98 9 17 9 15 9 9 1 39
输出
7
C++代码
//
// Created by HANWENKE on 2022-09-19.
//
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <map>
#include <algorithm>
using namespace std;
bool cmp( const pair<int,int>&a, const pair<int,int>&b){
return a.second>b.second;
}
/*解题思路
* 首先要找到众数,那么可以使用has_map
* 其次对hash_map进行排序,值最大的放到前面去
* 让后通过迭代器遍历--将最大的放到vector中
* 然后找到对应的中位数*/
int main(){
map<int,int>tmap;//key记录数字,val记录个数
string ss;
getline(cin,ss);
istringstream stemp(ss);
int temp;
while(stemp>>temp){
tmap[temp]++;
}
vector<pair<int,int>>arr(tmap.size());
int i=0;
for(auto &x:tmap){
arr[i++]=x;
}
//对map进行排序--需要重写比较函数
sort(arr.begin(),arr.end(),cmp);
vector<int>res;
//记录众数出现的次数
int key=arr.begin()->second;
for(int i=0;i<arr.size();i++){
if(arr[i].second==key){
res.push_back(arr[i].first);
}else{
break;
}
}
if(res.size()==1){
cout<<res[0];
return 0;
}
if(res.size()%2==1){
cout<<res[res.size()%2];
}else{
//如果长度是偶数--第一个数字则为 减去1除以2,第二个为直接除以2的值
int first=res[(res.size()-1)%2];
int second=res[res.size()%2];
cout<<(first+second)%2;
}
return 0;
}
0035-满足条件的两个集合
题目描述
同一个数轴x有两个点的集合A={A1,A2,…,Am}和B={B1,B2,…,Bm} A(i)和B(j)均为正整数
A、B已经按照从小到大排好序,AB均不为空
给定一个距离R 正整数,列出同时满足如下条件的 (A(i),B(j))数对
- A(i)<=B(j)
- A(i),B(j)之间距离小于等于R
- 在满足1,2的情况下每个A(i)只需输出距离最近的B(j)
- 输出结果按A(i)从小到大排序
输入描述
第一行三个正整数m n R
第二行m个正整数 表示集合A
第三行n个正整数 表示集合B
输入限制 1<=R<=100000 1<=n,m<=100000 1<= A(i),B(j) <= 1000000000
输出排序
每组数对输出一行 A(i)和B(j) 以空格隔开
输出输出样例
输入
4 5 5
1 5 5 10
1 3 8 8 20
输出
1 1
5 8
5 8
C++ 代码
//
// Created by HANWENKE on 2022-09-19.
//
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main(){
int m,n,r;//未初始化的全局变量存在.bss段
cin>>m>>n>>r;
//清空缓冲区--重置cin
cin.clear();
cin.sync();
vector<int>arr1;
vector<int>arr2;
string ss;
getline(cin,ss);
istringstream s1(ss);
int temp;
while(s1>>temp){
arr1.push_back(temp);
}
//清空缓冲区--重置cin
cin.clear();
cin.sync();
getline(cin,ss);
istringstream s2(ss);
while(s2>>temp){
arr2.push_back(temp);
}
for(auto &x:arr1){
for(auto &y:arr2){
if(x<=y&&(y-x)<=r){
//题目要求arr从小到大排序,因为arr1,和arr2本就有序,所以满足条件直接输出跳出循环就OK
cout<<x<<" "<<y<<endl;
break;
}
}
}
return 0;
}