bzoj 2456: mode 思维题 好题

题目描述:
给你一个 $n$ 个数的数列,其中某个数出现了超过 n div 2 次即众数,请你找出那个数。
空间大小:1mb

题解:
显然,我们是不能开任何数组的,此题专卡空间。
然而我们要求的东西也十分简单,就是出现次数最多的数。
出现次数最多,即代表着序列中没有数比答案数更多。
想象一下如果众数和其他的数字一一抵消的话最后剩下的肯定全都是答案。
我们只需设 2 个变量,分别代表当前数字编号,以及当前数字个数。
如果遇到新的数字,而当前数目为0,则将答案更新为新的数字。
最后剩下的一定是众数。

Code:

#include<cstdio>
int main(){
	//freopen("input.in","r",stdin);
	int n,cur,res=0;
	scanf("%d",&n);
	for(int i=1;i<=n;++i){
		int f;
		scanf("%d",&f);
		if(res==0){
			cur=f,res=1;
		}
		else 
		{
			if(f==cur) ++res;
			else --res;
		}
	}
	printf("%d",cur);
	return 0;
}

  

原文地址:https://www.cnblogs.com/guangheli/p/9889963.html