Description:
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: Floyd's Cycle Detection Algorithm Make Floyd's tortoise and hare great again!!!
The above first link explain and prove the Floyd's cycle detection Algorithm. The second one applies the principle to the question.
HashTable can also solve the question with O(n) Space complexity.
fun findDuplicate(nums: IntArray): Int {
var slow = 0
var fast = 0
while(true) {
slow = nums[slow]
fast = nums[nums[fast]]
if (fast == slow) break
}
var slow2 = 0
while(slow != slow2) {
slow = nums[slow]
slow2 = nums[slow2]
}
return slow
}