内存1M我开了5个int报空间了。由于出现的哪一个众数会大于n/2所以不同的数之间相互抵消,最后剩下来的一定是哪个众数
#include<cstdio>
int n,tot,x,y;
int main(){
scanf("%d",&n);
while(n--){
scanf("%d",&y);
if(tot==0)x=y,tot++;
else if(y==x)tot++;
else tot--;
}
printf("%d",x);
return 0;
}
本文介绍了一个高效的算法,用于从整数数组中找出出现次数超过一半的众数。该算法仅使用1M内存,并通过不断抵消不同数值来最终确定众数。
内存1M我开了5个int报空间了。由于出现的哪一个众数会大于n/2所以不同的数之间相互抵消,最后剩下来的一定是哪个众数
#include<cstdio>
int n,tot,x,y;
int main(){
scanf("%d",&n);
while(n--){
scanf("%d",&y);
if(tot==0)x=y,tot++;
else if(y==x)tot++;
else tot--;
}
printf("%d",x);
return 0;
}
461

被折叠的 条评论
为什么被折叠?