HDU1029——Ignatius and the Princess IV,HDU1030——Delta-wave,HDU1031——Design T-Shirt

目录

HDU1029——Ignatius and the Princess IV

题目描述

运行代码

代码思路

HDU1030——Delta-wave

题目描述

运行代码

代码思路

HDU1031——Design T-Shirt

题目描述

运行代码

代码思路

HDU1029——Ignatius and the Princess IV

题目描述

Problem - 1029

运行代码

#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;
}

代码思路

  1. 导入必要的头文件:代码开始时,导入了进行输入输出操作所需的iostream,用于跟踪每个数字频率的map,以及用于动态数组的vector

  2. 定义find函数:这个函数接收一个整数n,代表数组的大小,和一个整数向量arr。在函数内部:

    • 声明了一个count映射来保存每个数字的频率。
    • 遍历数组arr并递增映射中对应数字的计数器。
    • 然后在映射中搜索任何其频率大于或等于(n + 1) / 2的数字。如果存在这样的数字,它将作为结果返回。条件(n + 1) / 2确保当n是奇数时,考虑确切的一半,而当n是偶数时,向下取整给我们正确的阈值以确定主要元素。
  3. 定义main函数:这是程序开始执行的地方。在main函数中:

    • 它从标准输入读取数组的大小
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

筱姌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值