题目大意:
给出 n n n个数 a 1 , a 2 , . . . , a n − 1 , a n a_1,a_2,...,a_{n-1},a_n a1,a2,...,an−1,an,保证其中存在一个数 x x x满足在其中出现过的次数大于 ⌊ n 2 ⌋ \left \lfloor \frac{n}{2} \right \rfloor ⌊2n⌋,求最后的 x x x是多少。
n
<
=
500000
n<=500000
n<=500000
a
i
<
=
m
a
x
l
o
n
g
i
n
t
a_i<=maxlongint
ai<=maxlongint
分析:
我们可以
O
(
N
)
O(N)
O(N)的扫一遍,
每次保留一个数以及其的当前出现次数,如果过程中有一个数与其不同,则给这个数的当前出现次数
−
1
-1
−1,否则
+
1
+1
+1,
当当前出现次数为
0
0
0的时候,则替换掉,
因为满足
x
x
x出现的次数大于
⌊
n
2
⌋
\left \lfloor \frac{n}{2} \right \rfloor
⌊2n⌋,那么它的出现次数必定大于其他数字的出现次数之和,就有绝对的优势保留下来
因为内存吃的紧, C + + C++ C++开了 i o s t r e a m iostream iostream好像会炸。。
代码:
#include <cstdio>
using namespace std;
int n, x, now, total;
void read(int &x)
{
int f = 1; x = 0; char s = getchar();
while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); }
while (s >= '0' && s <= '9') { x = x * 10 + (s - '0'); s = getchar(); }
x = x * f;
}
int main()
{
read(n);
read(now); total = 1;
for (int i = 2; i <= n; i++)
{
read(x);
if (x == now) ++total; else --total;
if (!total) now = x, total = 1;
}
printf("%d\n", now);
return 0;
}