Find the Duplicate Number
Problem statement
You are given an integer array nums of length n + 1. Every value is in 1..n. Exactly one distinct value occurs more than once; it may occur more than twice. Return that value.
For this exercise, assume the conventional duplicate-number contract: do not modify the array, and aim for O(n) time and O(1) auxiliary space. The report names a variant without describing its changed rule, so this exercise uses the standard core.
Function
findDuplicate(nums: int[]) → intExamples
Example 1
nums = [1,3,4,2,2]return = 2Cycle entry differs from first value.
Example 2
nums = [3,1,3,4,2]return = 3Cycle-entry duplicate near the start.
Example 3
nums = [1,1]return = 1Minimum n equals one.
Constraints
1 <= n <= 1000.nums.length = n + 1and1 <= nums[i] <= n.- Exactly one distinct value is repeated; all other values occur at most once.