唯一出现的一位数(C++题解源程序)
发布时间
阅读量:
阅读量
136. 只出现一次的数字(C++|题解|源程序)
- 1.题目解析
-
- 哈希表
-
2.代码来源
-
3.原始程序
-
1.题解
哈希表
- 在C++语言中,unordered_map结构能够被用作哈希表;
- 当表内不存在对应项时,应将其添加至表中;
- 若表内已存在该元素,则应将其从表中移除;
- 经过上述操作后,最终表中将仅保留一个元素。
2.源码
class Solution {
public:
int singleNumber(vector<int>& nums) {
unordered_map<int, int> myMap;
int cnt = 0, res = 0;
for (auto num : nums) {
if (myMap.find(num) == myMap.end()) {
myMap[num] = 1;
}
else {
myMap.erase(num);
}
}
return myMap.begin()->first;
}
};
全部评论 (0)
还没有任何评论哟~
