33ms C++ Solution


  • 0
    W

    Its probably not the best, but its the only way that made sense to me at the time. I've read other posts, one where one person compared bits with the ^=, but I wanted to solve it my own way.

    class Solution {
    public:
        int singleNumber(vector<int>& nums) 
        {
            unordered_map<int,int> ans;
            //If the array is less than one size, return the first value
            if (nums.size()<=1)
                return nums[0];
                
            //Add all the values to the map, and their occurences
            for ( int i=0;i<nums.size();++i)
            {
                ans[nums[i]]++;
                
            }
            //Declare an iterator
            unordered_map<int,int>::iterator got;
            //Loop through the map and look for the key with a value of 1
            for (got=ans.begin();got!=ans.end();++got)
            {
               //if it's found a 1, return the key
               if(got->second==1)
                 return got->first;
                   
            }
            //return zero if nothing found
            return 0;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.