Numbers that only appear once

Given a non-empty array of integers, each element appears twice except one that appears only once. Find the element that appears only once.

illustrate:

Your algorithm should have linear time complexity. Can you do it without using extra space?

 

My solution: not very efficient

std::sort(nums.begin(), nums.end());
        for(int i=0 ; i<nums.size() ;)
        {
            if(nums[i] == nums[i+1])
            {
                if(i+2 < nums.size())
                {
                    i+=2;
                }
                else
                {
                    ++i;
                }
            }
            else
            {
                return nums[i];
            }
        }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325270556&siteId=291194637