Timus 1510. Order 找到出现次数过半的数

A New Russian Kolyan likes two things: money and order. Kolyan has lots of money, but there is no order in it. One beautiful morning Kolyan understood that he couldn't stand this any longer and decided to establish order in his money. He told his faithful mates to fetch the money from an underground depository, and soon his big room was filled up with red, green, and blue banknotes. Kolyan looked with disgust at this terrible mess. Now he wants to leave in his depository only banknotes of the same value and to give the rest of the money to the poor. He knows exactly that more than half banknotes have the same value. But in this mess it is impossible to understand which banknote is the most common.

Input

The first line contains the number of Kolyan's banknotes N(1 ≤ N≤ 500000). In the next Nlines, the values Kof these banknotes are given (0 ≤ K≤ 10 9). More than half of them are the same.

Output

Output the most common value.

Sample

input output
5
3
3
2
2
3
3


又是一个新的算法,原来可以这样查找的。

我的一句话理解的思想:

计算可以抵消的数量,那么如果一个数出现的次数超过半那么最终这个数肯定不会被抵消完。

这个思想叫Moore’s Voting Algorithm

有了这个思想武器之后,程序就可以写的很简单,可以很清楚看到怎么实现的,

参考资料可以看:

http://www.geeksforgeeks.org/majority-element/


#include <iostream>
using namespace std;

void main()
{
	int n = 0, a = 0, majority = 0, c = 1;
	cin>>n>>majority;
	while (--n)
	{
		cin>>a;
		if (majority == a) c++;
		else c--;
		if (0 == c) 
		{
			majority = a;
			c = 1;
		}
	}
	cout<<majority;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值