leetcode 287 Find the Duplicate Number
z

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.

Note:

  1. You must not modify the array (assume the array is read only).
  2. You must use only constant, O(1) extra space.
  3. Your runtime complexity should be less than O(n2).
  4. There is only one duplicate number in the array, but it could be repeated more than once.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public int findDuplicate(int[] nums) {
if(nums.length == 0) return -1;
if(nums.length == 1) return nums[0];
int slow = 0;
int fast = 0;
do{
slow = nums[slow];
fast = nums[nums[fast]];
}while(slow != fast);
fast = 0;
while(slow != fast){
slow = nums[slow];
fast = nums[fast];
}
return slow;
}
}
  • 可以看成是有环链表中找到环的entrypoint

  • fast指针和slow指针,设相交点为p

    • 设slow指针走的路程为s

    • faslt走的路程为2s

    • 2s = s + nC(C为cycle的长度)

    • 即slow走过的长度即为cycle的长度

    • 设startpoint到entrypoint的长度为x,则entrypoint到endpoint的长度为y

    • x + y = s = nC

    • x = nC - y

    • 即说明startpint到entrypoint的距离x和endpoint到entrypoint的距离相等。