一. 题目描述
Given an array nums containing n + 1
integers where each integer is between 1
and n
(inclusive), prove that at least one duplicate element must exist. Assume that there is only one duplicate number, find the duplicate one.
Note:
You must not modify the array (assume the array is read only).
You must use only constant extra space.
Your runtime complexity should be less than O(n^2)
.
There is only one duplicate number in the array, but it could be repeated more than once.
二. 题目分析
题目的大意是,给定一个包含n + 1
个整数的数组,其中每一个整数的大小均在[1, n]
之间,证明其中至少有一个重复元素存在。同时假设数组中只有一个数字出现重复,找出这个重复的数字。
注意事项:
- 不可以修改数组(假设数组是只读的)
- 只能使用常数空间
- 运行时间复杂度应该小于
O(n^2)
- 数组中只存在一个重复数,但是该数可能重复多次
题目的限定要求非常多,一开始并不能想到最优方法,这里给出一种新颖的方法:映射找环法,其实这种方法来源于链表找环。时间复杂度为O(n)
,空间复杂度O(1)
。
首先,假设一个数组中没有重复,则可以将数组的下标和其对应元素(1 ~ n
)一一的映射起来。举个例子,对于数组[4, 1, 3, 2]
,则映射关系为0 -> 4, 1 -> 1, 2 -> 3,3 -> 2
。
这个映射关系可表示一个函数f(n)
,其中n
是下标,f(n)
是映射到的数。如果我们从下标为0出发,根据这个函数计算出一个值,以这个值为新的下标,再用这个函数计算,以此类推,可以产生一个类似于链表的序列。
此时,如果数组本身有重复的元素,就会出现多对一的映射,比如数组[2, 1, 3, 1]
,则映射关系为:0 -> 2, {1, 3} -> 1, 2 -> 3
。熟悉链表的朋友知道,这一序列中出现了环路!与链表一致,如果遍历这个映射关系:0 -> 2 -> 3 -> 1 -> 1 -> 1 -> ...
,其中,环的起点就是题目所要求的重复的数。
所以该题实际上可转化为求环路起点,实现方法与Linked List Cycle II一题类似。同样,使用快慢(fast
,slow
)两个下标,从0
开始,快下标每次循环时映射两次,即:fast = num[num[fast]]
,而慢下标每次循环映射一次,即:slow = num[slow]
,直到fast == slow
,这个阶段相当于链表找环时,快指针与慢指针相遇,这一结论证明链表有环,对应到本题中,则能证明数组内有重复元素!
第二步,是找出这个重复元素,也就是找出环的入口,这时需要另一个变量finder
从下标0
出发,和fast
的操作一致,每次循环映射两次:fast = num[num[fast]]
,同时,slow
保持一次映射。当这两个下标相遇时,slow
就是环的起点,也就是重复的数。
参考:http://bookshadow.com/weblog/2015/07/10/leetcode-linked-list-cycle-ii/
三. 示例代码
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int slow = 0;
int fast = 0;
int finder = 0;
while (true)
{
slow = nums[slow];
fast = nums[nums[fast]];
if (slow == fast)
break;
}
while (true)
{
slow = nums[slow];
finder = nums[finder];
if (slow == finder)
return slow;
}
}
};
四. 小结
该题的思路相当新颖,不容易想到,此外,还有使用二分法来解决的方案,但不是最优方案。