Find the Duplicate Number

来源:互联网 发布:sql 按月分组 编辑:程序博客网 时间:2024/05/29 16:35
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.

使用映射找环法:

int findDuplicate(int* nums, int numsSize) {    int slow = 0;    int fast = 0;    do    {        slow = nums[slow];        fast = nums[nums[fast]];    }while(slow != fast);    int find = 0;    while(slow != find)    {        slow = nums[slow];        find = nums[find];    }    return find;}
数学分析:


如图,快慢指针同时从O点出发,慢指针每次移动一个单位,快指针每次移动两个单位,则在相遇点n,慢指针移动n个单位,快指针移动2n个单位。

那么问题就简单了:如果给一个指针find从头开始移动n个单位,和慢指针移动n个单位的结果就是又在n点相遇,但是m--->n点经过的点是完全一样的,所以第一次相遇的点就是环的起始点。



0 0