C++ 5lines O(n) solution with XOR


  • 0
    Z

    XOR operation has a property that x^x=0 and x^y^x = y so we can use it to find the element appears only once.

    class Solution {
    public:
        int singleNumber(vector<int>& nums) {
            int mask = 0;
            for(int i=0;i<nums.size();i++){
                mask = mask^nums[i];
            }
            return mask;
        }
    };
    

Log in to reply
 

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