[leetcode]-Find the Duplicate Number

来源:互联网 发布:易观智库 数据来源 编辑:程序博客网 时间:2024/05/29 10:58

题目

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.

c++代码

int findDuplicate3(vector<int>& nums){    if (nums.size() > 1)    {        int slow = nums[0];        int fast = nums[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;}

https://discuss.leetcode.com/topic/25913/my-easy-understood-solution-with-o-n-time-and-o-1-space-without-modifying-the-array-with-clear-explanation

n+1大小的数组中,数组元素范围为1到n其中只有一个数出现两次或者多次,找出重复出现的数,要求时间复杂度O(n),空间复杂度O(1)

比如数组a为[1,3,4,2,5,6,7,4],结果应该为4

a[0]->1a[1]->3a[2]->4……

将数组转换为图如下图所示:
图表示
4正是图中环路的入口

算法定义了slow和fast两个变量用于遍历

  1. slow每次走一步,fast每次走两步
    当slow==fast,则slow和fast在s处相遇。上个例子是在6 位置相遇
    其中
    slow路径: 0->1->3->2->4->5->6
    fast路径: 0->3->4->6->5->4->6

  2. slow从初始位置0出发,fast从上次相遇位置s出发,每次都走一步,则它们必定会在环路入口处4相遇
    slow路径: 0->1->3->2->4
    fast路径: 6->4->5->6->4

则得出解为4

它们必定会在入口处相遇解释如下:

  • 数组内容从1开始,则0必定在环路之外,即通过0入口可以找到环路入口
  • 相遇点s必定在环路之内
    这里写图片描述

起点A到入口B距离为 x
入口B到相遇点S距离为y
相遇点到入口点B距离为z

要证明fast从S出发,slow从A出发,它们必定相遇于B点等效于证明:
x = z + m(y+z), m为fast绕的圈数
由已知条件,fast速度是slow的两倍,同时从A出发,相遇与S,则有:
2(x+y)=x+y+ k(y+z)
=>
x+y = k(y+z)
=>
x = z + (k-1)(y+z)
=>
x = z + m(y+z)
得证。

0 0