Given an array aa of nn elements, print any value that appears at least three times or print -1 if there is no such value.
Input
The first line contains an integer tt (1 \leq t \leq 10^41≤t≤10
4
) — the number of test cases.
The first line of each test case contains an integer nn (1 \leq n \leq 2\cdot10^51≤n≤2⋅10
5
) — the length of the array.
The second line of each test case contains nn integers a_1, a_2, \dots, a_na
1
,a
2
,…,a
n
(1 \leq a_i \leq n1≤a
i
≤n) — the elements of the array.
It is guaranteed that the sum of nn over all test cases does not exceed 2\cdot10^52⋅10
5
.
Output
For each test case, print any value that appears at least three times or print -1 if there is no such value.
Sample 1
Inputcopy Outputcopy
7
1
1
3
2 2 2
7
2 2 3 3 4 2 2
8
1 4 3 4 3 2 4 1
9
1 1 1 2 2 2 3 3 3
5
1 5 2 4 3
4
4 4 4 4
-1
2
2
4
3
-1
4
Note
In the first test case there is just a single element, so it can’t occur at least three times and the answer is -1.
In the second test case, all three elements of the array are equal to 22, so 22 occurs three times, and so the answer is 22.
For the third test case, 22 occurs four times, so the answer is 22.
For the fourth test case, 44 occurs three times, so the answer is 44.
For the fifth test case, 11, 22 and 33 all occur at least three times, so they are all valid outputs.
For the sixth test case, all elements are distinct, so none of them occurs at least three times and the answer is -1.
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 2 * 1e5+20;
int main(void) {
int a[N];
int n;
cin >> n;
int m;
for (int i = 0; i < n; i++) {
int sum = 1;
int flag = 0;
cin >> m;
for (int j = 0; j < m; j++) {
cin >> a[j];
}
sort(a, a + m);
for (int j = 1; j < m; j++) {
if (a[j] == a[j - 1]) {
sum++;
}
else {
sum = 1;
}
if (sum >= 3) {
cout << a[j] << endl;
flag = 1;
break;
}
}
if (flag == 0) {
cout << -1 << endl;
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现