杭电oj HDOJ 1029 Ignatius and the Princess IV

杭电oj HDOJ 1029 Ignatius and the Princess IV

题目来源:http://acm.hdu.edu.cn/showproblem.php?pid=1029

Problem Description

“OK, you are not too bad, em… But you can never pass the next test.” feng5166 says.

“I will tell you an odd number N, and then N integers. There will be a special integer among them, you have to tell me which integer is the special one after I tell you all the integers.” feng5166 says.

“But what is the characteristic of the special integer?” Ignatius asks.

“The integer will appear at least (N+1)/2 times. If you can’t find the right integer, I will kill the Princess, and you will be my dinner, too. Hahahaha…” feng5166 says.

Can you find the special integer for Ignatius?

Input

The input contains several test cases. Each test case contains two lines. The first line consists of an odd integer N(1<=N<=999999) which indicate the number of the integers feng5166 will tell our hero. The second line contains the N integers. The input is terminated by the end of file.

Output

For each test case, you have to output only one line which contains the special number you have found.

题目大意

测试用例中给出一串长度为 N N N的整数序列,找出这串整数中那个出现次数大于等于其长度的整数。

解题思路

本题的思想无非就是“统计”二字,但是这个整数串的长度很大,如果简单地使用“循环”和“数组”就会出现“超时”的情况,所以可以尝试使用“map容器”。

本人的C++解决方案

#include <iostream>
#include <stdio.h>
#include <map>
using namespace std;

int main()
{
	int N, n, i, res;
	map<int, int> m;
	map<int, int>::iterator iter;
	while (cin >> N) {
		res = 0;
		for (i = 0; i < N; i++) {
			cin >> n;
			iter = m.find(n);
			// 找到元素
			if (iter != m.end()) {
				iter->second++;
				if (iter->second == (N + 1) / 2) {
					res = iter->first;
				}
			}
			// 未找到元素
			else {
				m.insert(map<int, int>::value_type(n, 1));
			}
		}
		m.clear();
		printf("%d\n", res);
	}
	return 0;
}

本题涉及到的关于“map容器”的内容:

  1. 首先要引用相关头文件:#include <map>
  2. iterator find(const Key& key):用于寻找容器中的“键值对”,“key”为要搜索的映射中的元素的排序键与之匹配的键值,返回值为有指定键的元素的位置的迭代器,如果找不到具有键的匹配项,则引用映射中map::end()最后一个元素后面的位置。
  3. pair<iterator, bool> insert(value_type&& _Val):用于将一个元素或元素范围插入到映射中,“val”为要插入到映射中的元素的值。
  4. void clear():用于清除容器的所有元素。

上述相关函数还有许多其他用法,请读者自行寻找查阅。

代码通过HDOJ平台运行检查,如果发现错误,欢迎指出和纠正,谢谢!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值