hodj 1029 Ignatius and the Princess IV

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

直接开一个大点的数组,数据竟然过了

    hdoj 1029 Ignatius and the Princess IV
	题目大意:找出数列中特殊的数,特殊的数为出现次数大于(n+2)/2的数
	解题思路1:直接用一个数组记录每一个数字出现的次数 
#include<stdio.h>
#include<string.h>
int arr[1000010];
int main(){
	int N,num;
	while(scanf("%d",&N)!=EOF){
		int ans=0;
		memset(arr,0,sizeof(arr));
		for(int i=1;i<=N;i++){
			scanf("%d",&num);
			arr[num]++;
			if(arr[num]>=(N+1)/2){
				ans=num;
			}
		}
		printf("%d\n",ans);
	}
	return 0;
} 

有好多数没有出现,用map可以节省一些空间

#include<stdio.h>
#include<string.h>
#include<map>
using namespace std; 
int main(){
	int N,num;
	map<int,int>m;
	while(scanf("%d",&N)!=EOF){
		int ans=0;
		m.clear();
		for(int i=1;i<=N;i++){
			scanf("%d",&num);
			m[num]++;
			if(m[num]>=(N+1)/2){
				ans=num;
			}
		}
		printf("%d\n",ans);
	}
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/Dear_Jia/article/details/82352683