1. 程式人生 > >2456. mode【亂搞】

2456. mode【亂搞】

input 數列 出現 pos amp 我們 CP pre 亂搞

Description

給你一個n個數的數列,其中某個數出現了超過n div 2次即眾數,請你找出那個數。

Input

第1行一個正整數n。
第2行n個正整數用空格隔開。

Output

一行一個正整數表示那個眾數。

Sample Input

5
3 2 3 1 3

Sample Output

3

HINT

100%的數據,n<=500000,數列中每個數<=maxlongint。

因為眾數要超過一半,所以我們讓兩個不相同的數相互抵消,最後剩下的就是眾數了

#include<cstdio>
using namespace std;
int n,cnt,x,num;
int main()
{
	scanf("%d",&n);
	for (int i=1;i<=n;++i)
	{
		scanf("%d",&x);
		if (cnt==0)
		{
			cnt++;
			num=x;
		}
		else
		if (x!=num)
			cnt--;
		else
			cnt++;
	}
	printf("%d",num);
}

2456. mode【亂搞】