Short Solution Using XOR [AC]

  • 0

    XOR with a number itself returns 0. So, we will eliminate all the duplicates using xor. The final element left will be our result.

    class Solution {
        int singleNumber(vector<int>& nums) {
            int n = nums.size(), ans = nums[0];
            for(int i=1;i<n;i++) ans = ans^nums[i];
            return ans;

Log in to reply

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