描述
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:
1 | Input: [1,3,4,2,2] |
Example 2:
1 | Input: [3,1,3,4,2] |
Note:
- You must not modify the array (assume the array is read only).
- You must use only constant, O(1) extra space.
- Your runtime complexity should be less than O(n2).
- There is only one duplicate number in the array, but it could be repeated more than once.
分析
和 142. Linked List Cycle II 的思路基本一致。这道题可以把数组当做一个图,对于数组中的值,i -> A[i]
是一条有向连接,由于数组的长度是 n+1, 而值的范围为 1~n
,重复的那个值就相当于有两个节点指向它,因此这个图中一定存在环。求这个环的入口,逻辑就跟 142. Linked List Cycle II 这道题没什么区别了。
解决方案1(Java)
1 | class Solution { |
解决方案2(Golang)
1 | func findDuplicate(nums []int) int { |
相关问题
- (M) Linked List Cycle II
- (H) First Missing Positive
- (M) Missing Number
- (E) Single Number
- (E) Set Mismatch