Find the Duplicated Number
Question:
这个题呢, 难点就是在于must solve the problem without modifying the array nums,。
如果它允许modify array nums, 那么这个题的解法就太多了。比较好的解法有一个cyclic sort 找duplicated.
但是这个题主要考查的是two pointers, 和 find cycle entrance of linked list.
不太好理解的就是怎么把array of numbers 比作linked list cycle.
不太清楚这里怎么回事的同学建议先去做一下 Array Nesting那道题.
把array 变成 一个linkedlist path 就是用的nesting的方法
这儿的解释不太正确!
//
通过实践和测试, 我发现当一个array是number[1,n]的permutation时, 这个array是不会出现cycle的. 换句话说就是一个完整的path, 到最后sink node.
ex:
1,3,4,2,5
nums[0] = 1 -> nums[1] = 3 -> nums[3] = 2 -> nums[2] = 4 -> nums[4] = 5 -> nums[5] = sink node
顺序为: 1,3,2,4,5
3,4,5,1,2
顺序为: 3,1,4,2,5
//
因为array of num里的每一个num 都是unique 的, 所以每一个index的nesting都对应独特的下一个index, 所以才会形成一个完整的path. 所以如果我们把其中一个num的数值改变成一个duplicated num, 那么就会有两个index 指向同一个node. 就形成了cycle.
ex:
1,3,4,2,2
nums[0] = 1 -> nums[1] = 3 -> nums[3] = 2 -> nums[2] = 4 -> nums[4] = 2 -> nums[4] -> nums[4] = 2 -> nums[2] = 4 = cycle
理解上面这个例子之后, 我们就理解如何把array of num 比作linked list cycle 了.
那么我们就可以按照find linkedlist cycle entrance 那个题同样的方法 做这道题.
class Solution {
public int findDuplicate(int[] nums) {
int slow = 0, fast = 0;
do {
slow = nums[slow];
fast = nums[nums[fast]];
} while(slow != fast);
slow = 0;
while(slow != fast) {
slow = nums[slow];
fast = nums[fast];
}
return slow;
}
}
做点更改, 其实上面说的不太对. 并不是 “一个array是number[1,n]的permutation时, 这个array是不会出现cycle的”,
我们只是能确定在[1,n]数字的permutation里, 然后length是n+1. 我们能确定一定是有cycle的.
举例子:
如果是: 5,4,3,2,1
会发现4 和 1 在无限循环. 但此时这个例子里没有duplicated. (因为5在index 0) ,但如果length 是 n+1
那不管我们再加任何哪一个integer到这个例子里, 那个duplicated 都一定是cycle entrance
5, 5, 4, 3, 2, 1