website/content.en/ChapterFour/0200~0299/0287.Find-the-Duplicate-Number.md
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
Example 1:
Input: [1,3,4,2,2]
Output: 2
Example 2:
Input: [3,1,3,4,2]
Output: 3
Note:
Given n + 1 numbers, each of which takes a value from 1 to n, and the same number may appear multiple times. Find the duplicate number among these numbers. The time complexity should preferably be lower than O(n^2), and the space complexity should be O(1).
package leetcode
import "sort"
// Solution 1: Fast and slow pointers
func findDuplicate(nums []int) int {
slow := nums[0]
fast := nums[nums[0]]
for fast != slow {
slow = nums[slow]
fast = nums[nums[fast]]
}
walker := 0
for walker != slow {
walker = nums[walker]
slow = nums[slow]
}
return walker
}
// Solution 2: Binary search
func findDuplicate1(nums []int) int {
low, high := 0, len(nums)-1
for low < high {
mid, count := low+(high-low)>>1, 0
for _, num := range nums {
if num <= mid {
count++
}
}
if count > mid {
high = mid
} else {
low = mid + 1
}
}
return low
}
// Solution 3
func findDuplicate2(nums []int) int {
if len(nums) == 0 {
return 0
}
sort.Ints(nums)
diff := -1
for i := 0; i < len(nums); i++ {
if nums[i]-i-1 >= diff {
diff = nums[i] - i - 1
} else {
return nums[i]
}
}
return 0
}