012 - leedcode第136题只出现一次的数字——基于c++

int Solution::singleNumber(vector& nums)
{
    /**
     *这个题很特殊:它要求最好有线性复杂度,并且不使用额外的空间。
     *
     *利用数字之间的 异或 运算,异或 运算的性质有 a^b^c = a^c^b
     *如 1^2^1 = 1^1^2 = 0^2 = 2 
     * 
     */
     int result = nums[0];
     for(int i = 1; i < nums.size(); i++)
     {
         result = result ^ nums[i];
     }
     return result;
}

 

你可能感兴趣的:(leedcode,c++)