HDU1029——Ignatius and the Princess IV

题意:求N个数中出现次数大于等于(N+1)/2的数。因为N是奇数,所以也就是求出现次数一半以上的数。

定义变量ans=第一个数、time=1,向后循环如果和ans相等time++,否则time--,当tine减到0时说明ans中的数在整体中出现的次数一定不多于一半,将ans赋为当前值继续循环。

View Code
#include<stdio.h>

int main()
{
int n;
while(scanf("%d", &n) != EOF)
{
int num, time = 0, ans;
while(n--)
{
scanf("%d", &num);
if(0 == time)
{
ans = num;
time = 1;
}
else
{
if(ans == num)
time++;
else
time--;
}
}
printf("%d\n", ans);
}
return 0;
}

 

posted @ 2011-12-02 20:44  1050768624  阅读(165)  评论(0编辑  收藏  举报