首页 > 代码库 > 2456: mode
2456: mode
2456: mode
Time Limit: 1 Sec Memory Limit: 1 MBSubmit: 4798 Solved: 2009
[Submit][Status][Discuss]
Description
给你一个n个数的数列,其中某个数出现了超过n div 2次即众数,请你找出那个数。
Input
第1行一个正整数n。
第2行n个正整数用空格隔开。
Output
一行一个正整数表示那个众数。
Sample Input
5
3 2 3 1 3
3 2 3 1 3
Sample Output
3
HINT
100%的数据,n<=500000,数列中每个数<=maxlongint。
zju2132 The Most Frequent Number
Source
鸣谢 黄祎程
/* * Author: lyucheng * Created Time: 2017年05月14日 星期日 17时17分40秒 * File Name: /media/lyucheng/Work/ACM源代码/数学--数论/乱搞/BZOJ-2456.cpp *//* 题意:给你一个n个数的序列,ai<=longmaxint,然后让你求出出现次数超过 n/2的众数 * * 思路:map映射不可行,可以离散化优化一下,还是超时,可能不是超时的问题,应该是超内存,显然500000个LL开数组肯定会超时的 * 所以不能开数组,看了题解才发现这个神奇的算法,众数肯定是出现次数最多的那个数,现在让所有不相同的数进行两两抵消 * 那么剩下的肯定是数量最多的那一个了 * */#include <cstdio>int n;int x;int now;//当前遍历到的数int res;//表示现在相同的数的数量int main(){ //freopen("in.txt","r",stdin); //freopen("out.txt","w",stdout; scanf("%d",&n); for(int i=1;i<=n;i++){ scanf("%d",&x); if(x==now) res++;//如果两个数相等,那么相等的数量+1 else if(res==0){//如果当前没有相等的数了 now=x;res=1; }else res--;//不相等就-1 } printf("%d\n",now); return 0;}
2456: mode
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。