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.
public int findDuplicatesec(int[] nums) {
// Find the intersection point of the two runners.
//定义快慢指针
int tortoise = nums[0];
int hare = nums[0];
//将数组看成链表
do {
tortoise = nums[tortoise];
hare = nums[nums[hare]];
} while (tortoise != hare);
// Find the "entrance" to the cycle.
//第二部分,找到环的入口
int ptr1 = nums[0];
int ptr2 = tortoise;
while (ptr1 != ptr2) {
ptr1 = nums[ptr1];
ptr2 = nums[ptr2];
}
return ptr1;
主要用到了环检测算法,该算法主要分为两部分
算法可以分成两个步骤,第一个步骤是确定链表是否有环,第二个步骤是确定环的入口点在那里。
步骤1
首先,我们初始化两个指针,一个快速的 hare 指针,一个慢的Tortoise 指针。让hare 一次走两个节点,Tortoise 一个节点。最终,Tortoise 和hare 总会在相同的节点相遇,这样就可以证明是否有环。
步骤2
考虑到步骤1发现一个交叉点,步骤2继续寻找环入口的节点。为此,我们初始化两个指针:ptr1指向列表头部的指针,指向ptr2交叉点的指针 。然后,我们把他们每个每次前进1个节点,直到他们相遇; 他们相遇的节点是环的入口,我们就可以得出结果。
https://www.jianshu.com/p/4f7dc8b9aa3c