- 题目:一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
- 思路:
- 使用map,遍历一次统计所有数字出现的次数
- 再遍历一次map,找到只出现一次的两个数字
- 启发或者坑
- 大概是再次熟悉了指针的赋值
- 代码
class Solution { public: map<int, int> mark; void FindNumsAppearOnce(vector<int> data,int* num1,int *num2) { vector<int> res; map<int, int>::iterator it; for (int i = 0; i < data.size(); i++) { it = mark.find(data[i]); if (it == mark.end()) { mark.insert(pair<int,int>(data[i], 1)); } else { //有人出现第二次了 mark[data[i]] = 2; } } for (it = mark.begin();it != mark.end(); it++){ if (it->second==1){ res.push_back(it->first); } } if (res.size() == 2) { num1[0] = res[0]; num2[0] = res[1]; } } };
剑指offer 35.数组中只出现一次的数字
猜你喜欢
转载自blog.csdn.net/Alexia23/article/details/103866646
今日推荐
周排行