287. Find the Duplicate Number

Posted 积少成多

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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:

  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.

==============================

题目:如果把这个数组看做是链表,数组中元素值当做链表节点中next指针,

我们可以发现这道题就是在求 链表中环的  开始节点

有关环的开始节点证明,可以看这里:  [http://www.cnblogs.com/li-daphne/p/5551048.html]

=========

思路:利用fast/slow方法(slow的步长为1,fast的步长为2),找到"链表"相遇的地方,

这时候fast指向"链表"的开始位置,slow接着遍历(fast和slow的步长都为一).

当fast/slow再次相遇的地方,就是"链表环"的入口,即数组中 重复元素.

===========

代码:

class Solution {
public:
    int findDuplicate(vector<int>& nums) {
        if(nums.size()>1){
            int fast = nums[nums[0]];
            int slow = nums[0];
            while(slow!=fast){
                slow = nums[slow];
                fast = nums[nums[fast]];
            }

            fast = 0;
            while(fast != slow){
                fast = nums[fast];
                slow = nums[slow];
            }
            return slow;
        }
        return -1;
    }
};

 

以上是关于287. Find the Duplicate Number的主要内容,如果未能解决你的问题,请参考以下文章

287. Find the Duplicate Number

287. Find the Duplicate Number

287. Find the Duplicate Number

287. Find the Duplicate Number

287. Find the Duplicate Number

287. Find the Duplicate Number