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