寻找数组中只出现一次的最小数的索引
寻找数组中只出现一次的最小数的索引
给定一个长度为 n 的整数数组 a1,a2,…,an。
请你找到数组中只出现过一次的数当中最小的那个数。
输出找到的数的索引编号。
a1 的索引编号为 1,a2 的索引编号为 2,…,an 的索引编号为 n。
输入
第一行包含整数 T,表示共有 T 组测试数据。
每组数据第一行包含整数 n。
第二行包含 n 个整数 a1,a2,…,an。
输出
每组数据输出一行结果,即满足条件的数的索引编号,如果不存在满足条件的数,则输出 -1。
样例输入
2
2
1 1
3
2 1 3
样例输出
-1
2
提示
1≤T≤2×104,
1≤n≤2×105,
1≤ai≤n,
同一测试点内的所有n的和不超过2×105
C++代码实现
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
int main() {
int T;
cin >> T;
while (T--) {
int n;
cin >> n;
vector<int> nums(n);
unordered_map<int, int> count;
for (int i = 0; i < n; i++) {
cin >> nums[i];
count[nums[i]]++;
}
int minIndex = -1;
for (int i = 0; i < n; i++) {
if (count[nums[i]] == 1) {
if (minIndex == -1 || nums[i] < nums[minIndex]) {
minIndex = i;
}
}
}
cout << minIndex + 1 << endl;
}
return 0;
}
原文地址: https://www.cveoy.top/t/topic/qktQ 著作权归作者所有。请勿转载和采集!