meta data for this page
  •  

Find the Duplicate Number

Leetcode


Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.

There is only one repeated number in nums, return this repeated number.

You must solve the problem without modifying the array nums and uses only constant extra space.

Example 1:

Input: nums = [1,3,4,2,2]
Output: 2

Solution 1

Solution 1

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