目录
HDU1029——Ignatius and the Princess IV
HDU1029——Ignatius and the Princess IV
题目描述
运行代码
#include<iostream>
#include<map>
#include<vector>
using namespace std;
int find(int n, vector<int>arr) {
map<int, int>count;
for (int num:arr) {
count[num]++;
}
int maxcount = 0;
int special = -1;
for (const auto& pair : count) {
if (pair.second >= (n + 1) / 2) {
special = pair.first;
break;
}
}
return special;
}
int main() {
int n;
while (cin >> n) {
vector<int>arr;
int num;
for (int i = 0; i < n; i++) {
cin >> num;
arr.push_back(num);
}
int res = find(n, arr);
cout << res << endl;
}
return 0;
}
代码思路
-
导入必要的头文件:代码开始时,导入了进行输入输出操作所需的
iostream
,用于跟踪每个数字频率的map
,以及用于动态数组的vector
。 -
定义
find
函数:这个函数接收一个整数n
,代表数组的大小,和一个整数向量arr
。在函数内部:- 声明了一个
count
映射来保存每个数字的频率。 - 遍历数组
arr
并递增映射中对应数字的计数器。 - 然后在映射中搜索任何其频率大于或等于
(n + 1) / 2
的数字。如果存在这样的数字,它将作为结果返回。条件(n + 1) / 2
确保当n
是奇数时,考虑确切的一半,而当n
是偶数时,向下取整给我们正确的阈值以确定主要元素。
- 声明了一个
-
定义
main
函数:这是程序开始执行的地方。在main
函数中:- 它从标准输入读取数组的大小