Leetcode287. Find the Duplicate Number
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:
- You must not modify the array (assume the array is read only).
- You must use only constant, O ( 1 ) O(1) O(1) extra space.
- Your runtime complexity should be less than O ( n 2 ) O(n^2) O(n2)
- There is only one duplicate number in the array, but it could be repeated more than once.
解法一:快慢指针
① 如果n个元素的数组中没有重复元素,且元素的取值范围为[1,n]。则把数组下标[0,n-1]放在集合a,元素的值[1,n]放在集合b,则集合a到集合b的映射一定是一对一的。
② 现在往数组里任意加了一个元素取值在[1,n],则集合a到集合b的映射不是一对一的,一定有两个下标指向同一个元素。
- 数组中有一个重复的整数 <=> 链表中存在环
- 找到数组中的重复整数 <=> 找到链表的环入口
把这个数组看做是带环的链表,要找的重复元素就是环的入口,即Leetcode142. Linked List Cycle II,所以这题的关键就是要理解如何将输入的数组看作为链表。
-
假设数组中没有重复元素,如[1,3,4,2],把下标与值的对应关系 index->number 写出来①0–>1 ②1–>3 ③2–>4 ④3–>2。我们可以得到一个链表:0->1->3->2->4->null,即①->②->④->③->null。这样我们就把数组转换成了链表。
注:上述只是为了帮助理解数组转换为链表的情况,实际上这个转换有可能被终止,比如[1,5,3,2,4],把下标与值的对应关系写出来①0–>1 ②1–>5 ③2–>3 ④3–>2 ⑤4–>4,这样在①->②的时候就已经终止了。但是这种情况在数组中有重复元素的时候不会出现,因为数组元素个数为n+1个,元素值为[1,n],不会发生数组越界的情况。
-
假设数组中有重复元素,如[1,5,3,2,3,4],同理写出对应关系①0–>1 ②1–>5 ③2–>3 ④3–>2 ⑤4–>3 ⑥5–>4。可以得到另一个链表:0->1->5->4->3->2->3->2…,即 ①->②->⑥->⑤->④ <-> ③,链表在③④这里成环了,
上面还有一种特殊情况,即元素的index=number,如[1,5,3,2,4,3],循环是0->1->5->3->2->3->2,并不会索引到4,但不会影响到结果
根据上述数组转链表的映射关系,可推出
1慢指针走一步slow = slow.next
=> slow = nums[slow]
1快指针走两步fast = fast.next.next
=> fast = nums[nums[fast]]
public class Solution {
public int findDuplicate(int[] nums) {
int fast = nums[0], slow = nums[0];
while (true) {
fast = nums[nums[fast]];
slow = nums[slow];
if (fast == slow) break;
}
fast = nums[0];
while (slow != fast) {
slow = nums[slow];
fast = nums[fast];
}
return fast;
}
}
解法二 二分查找
想不来