题意:给定一个序列L(L最多有250000个数据),求这个数组的主元素。主元素x定义如下:x在序列中出现的次数大于|L|/2个。
输入:
5 2 1 2 3 2
8 3 3 4 4 4 4 3 4
输出:
2
4
思路:用一个变量now保存当前的候选主元素。num变量用来计数。注意此题假设数组中必存在主元素,实际上如果没有这个假设,最后now元素保存的数值不一定是主元素,还需要扫一遍数组来确定其是否为主元素。
#include <stdio.h>
#include <string.h>
#define T long long
#define N 250005
T s;
int n;
int main(){
freopen("a.txt","r",stdin);
while(scanf("%d",&n)!=EOF){
T now;
int i,num=1;
scanf("%lld",&s);
now = s;
for(i = 1;i<n;i++){
scanf("%lld",&s);
if(now == s)
num++;
else{
if(num)
num --;
else
now = s;
}
}
printf("%lld\n",now);
}
return 0;
}