劍指offer:找出數組中只出現一次的兩個數字

一個整型數組裏除了兩個數字之外,其他的數字都出現了偶數次。請寫程序找出這兩個只出現一次的數字。

#include<unordered_map>
class Solution {
public:
//num1和num2分別保存這兩個只出現一次的數字
    void FindNumsAppearOnce(vector<int> data,int* num1,int *num2) {
        int len=data.size();
        unordered_map<int,int> hashMap;
        for(int i=0;i<len;i++)
        {
            if(hashMap.find(data[i])==hashMap.end())
            {
                hashMap[data[i]]=1;
            }
            else
            {
                hashMap[data[i]]++;
            }
        }
        unordered_map<int,int>::iterator it;
        vector<int> res;
        for(it=hashMap.begin();it!=hashMap.end();it++)
        {
            if(it->second==1)
            {
                res.push_back(it->first);
            }
        }
        *num1=res[0];
        *num2=res[1];
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章