天天看點

leetcode——第137——隻出現一次的數字

題目:

給你一個整數數組 nums ,除某個元素僅出現 一次 外,其餘每個元素都恰出現 三次 。請你找出并傳回那個隻出現了一次的元素。

class Solution {
public:
    int singleNumber(vector<int>& nums) 
    {
        // unordered_map<int,int> numMap;
        // for(int i=0; i<numMap.size(); i++)
        // {
        //     // 把nums中的·元素值當做 key ,出現的次數作為 value
        //     numMap[nums[i]]++;
        // }
        // for(auto it : numMap)
        // {
        //     if(it.second == 1)
        //     {
        //         return it.first;
        //     }
        // }
        // return 0;

        unordered_map<int,int>map;
        for(auto & num:nums){
            map[num]++;
        }
        for(auto & num:nums){
            if(map[num]==1)return num;
        }
        return 0;

    }
};