题解 | #出现一次的数字ii#哈希表
出现一次的数字ii
https://www.nowcoder.com/practice/1097ca585245418ea2efd0e8b4d9eb7a
class Solution { public: /** * * @param A int整型一维数组 * @param n int A数组长度 * @return int整型 */ int singleNumber(int* A, int n) { // write code here unordered_map<int, int> map; // 统计每个数字出现的次数 for (int i = 0; i < n; i++) { map[A[i]]++; } // 找到并返回只出现一次的数字 for (const auto& pair : map) { if (pair.second == 1) { return pair.first; } } // 如果没有找到这样的元素,可以返回一个默认值或抛出异常 // 这里假设总是存在一个唯一的元素,所以实际上不会走到这里 return -1; // 可以选择适当的默认值 } };