leetcode 287 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.
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.
1 | class Solution { |
可以看成是有环链表中找到环的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的距离相等。