【1186】出现次数超过一半的数

【问题描述】
       给出一个含有n(0 < n ≤ 1000)个整数的数组,请找出其中出现次数超过一半的数。数组中的数大于-50且小于50。。
【输入】
       第一行包含一个整数n,表示数组大小;
       第二行包含n个整数,分别是数组中的每个元素,相邻两个元素之间用单个空格隔开。。
【输出】
       如果存在这样的数,输出这个数;否则输出no。。
【输入样例】
       3
       1 2 2
【输出样例】
       2
【参考程序】

#include <cstdio> 
#include <iostream>
#include <cstring> 
using namespace std;

int main() {
	int n, x, a[1001];
	memset(a, 0, sizeof(a));
	
	cin >> n;
	for (int i=1; i<=n; i++) {
		cin >> x;
		a[x+50]++;					// 对x的数量加1,加50是因为x可能为负数(x>=-50) 
		if (a[x+50] > (n/2)) {		// 判断当前的数x的数量是否超过一半 
			printf("%d", x);
			return 0; 
		}
	}
	printf("no");					// 如果程序没结束就表示没有出现次数超过一半的数 
		
	return 0;
}

发布了66 篇原创文章 · 获赞 0 · 访问量 1217

猜你喜欢

转载自blog.csdn.net/developer_zhb/article/details/105467277