HDU - 1029 - Ignatius and the Princess IV

Ignatius and the Princess IV

HDU - 1029

题意:

给出n(奇数)个数字,找出出现至少(n+1)/2 次的数字。

分析:

找到在一段序列中出现次数一半以上的数字。如果用哈希,会超内存,用map,由于数据量是1e6,恐怕会超时,所以还是另辟途径。想了半天还是去看了题解,被他们新奇的解法震撼到了。巧妙利用出现次数必须大于二分之一这一特性,利用逐一抵消,最后留下的肯定就是答案,比如序列

1 2 1 1 3 1 5

1和2抵消,然后1,1和3,5抵消,留下的还是1。

再比如

1 3 5 1 3 1 2 5 3 1 1 1 1

1,3不同,抵消,5,1不同,抵消,3,1不同,抵消,2,5 不同,抵消,3,1不同,抵消。

如何模拟抵消这一状态呢,我们可以先记录下第一个值last,然后如果下一个数和这个数相同,那么num++,如果不同,num--。如果num==0,那么把last等于当前数字,并且num = 1

int n;
int a[1000001];
int main() 
{
    while(cin>>n)
    {
        for(int i=1;i<=n;i++)
            scanf("%d",&a[i]);
        int last = a[1],num=1;
        for(int i=2;i<=n;i++)
            if(a[i] == last)
                num++;
            else if(num==0)
            {
                last = a[i];
                num++;
            }
            else
                num--;
        cout<<last<<endl;
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/1625--H/p/9766651.html