Java O(n*log n) time, but very easy to understand


  • -2

    First I sort the array, then if there are two consecutive same numbers, we have detected the duplicate.

    public int findDuplicate(int[] nums) {
        Arrays.sort(nums);
        int mask = nums[0];
        
        for(int i = 1; i < nums.length; i++){
            mask ^= nums[i];
            if(mask == 0){
                return nums[i];
            }
            mask = nums[i];
        }
        return -1;
    }

Log in to reply
 

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