您的位置:首页 > 其它

九度 题目1370:数组中出现次数超过一半的数字

2014-05-23 12:39 274 查看
题目来源:http://ac.jobdu.com/problem.php?pid=1370

时间限制:1 秒

内存限制:32 兆

特殊判题:

提交:2022

解决:616

题目描述:
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。

输入:
每个测试案例包括2行:

第一行输入一个整数n(1<=n<=100000),表示数组中元素的个数。

第二行输入n个整数,表示数组中的每个元素,这n个整数的范围是[1,1000000000]。

输出:
对应每个测试案例,输出出现的次数超过数组长度的一半的数,如果没有输出-1。

样例输入:
9


1 2 3 2 2 2 5 4 2


样例输出:
2


#include <iostream>
#include <cstdio>
#include <cstring>
#include <climits>

using namespace std;

const int MAXN = 100010;

bool CheckMoreThanHalf(int* arr, int n, int res)
{
int i, iTimes = 0;
for(i = 0; i < n; ++i)
if(res == arr[i])
iTimes++;
if(2*iTimes > n)
return true;
else
return false;
}

int main()
{
int iPos, iTimes;
int n, i;
int arr[MAXN];
while(~scanf("%d", &n))
{
scanf("%d", &arr[0]);
iPos = arr[0];
iTimes = 1;
for(i = 1; i < n; ++i)
{
scanf("%d", &arr[i]);
if(iTimes == 0)
{
iPos = arr[i];
iTimes = 1;
}
else if(iPos == arr[i])
iTimes++;
else
iTimes--;
}
if(CheckMoreThanHalf(arr, n, iPos))
printf("%d\n", iPos);
else
printf("-1\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐