Find the Duplicated Number

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值