5-lines C++ Solution using XOR


  • 0
    F

    No need to loop through till the end except for the last duplicate number. However, sorting is used as numbers may not be sorted in the given vector.

    int findDuplicate(vector<int>& nums) {        
          sort(nums.begin(),nums.end());
          int i=0;
          for(i=0;i<nums.size();i++)
              if((nums[i] ^ i) ==0)break;          
          return i;   
        }
    '

Log in to reply
 

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