题意:给一组数字,求其中数量超过数组一半的数字。
思路:
由于数字的最大值为2^24,故无法开数组来存。
所以可以用哈希。
但哈希小题大做了,这题的特性是“数量超过一半”
根据剑指offer里的题,我们知道既然超过一半,那么维持一个当前颜色c,每当颜色相同,颜色数量+1,颜色不同,数量-1。而因为答案的数量超过一半,故维持到最后,当前颜色c一定是他。
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<stack>
#include<vector>
#include<queue>
#include<string>
#include<map>
using namespace std;
#define INF 99999999
#define M 605
#define N 805
int main()
{
int i,n,m,color;
scanf("%d%d",&n,&m);
int cn=0;
int nowc;
color=-1;
cn=1;
for(i=0;i<n*m;i++)
{
scanf("%d",&color);
if(color==nowc)
cn++;
else
{
cn--;
if(cn==0)
{
nowc=color;
cn++;
}
}
}
printf("%d\n",nowc);
}