classSolution { public: intsingleNumber(vector<int>& nums){ unordered_map<int, int> hashTable; for (int i = 0; i < nums.size(); i++) hashTable[nums[i]]++; int ans; for (unordered_map<int, int>::iterator it = hashTable.begin(); it != hashTable.end(); ++it) if (it->second == 1) { ans = it->first; break; }
return ans; } };
2. 位运算异或
偶数个相同的数据异或之后变成0,而任何数异或0还是它本身。 时间O(n),空间O(1)。
1 2 3 4 5 6 7 8 9
classSolution { public: intsingleNumber(vector<int>& nums){ int ans = 0; for (int i = 0; i < nums.size(); i++) ans ^= nums[i]; return ans; } };