LeetCode:M-287. Find the Duplicate Number

LeetCode链接


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.

class Solution {
    //可以理解成链表
    //由于值为1~n,则0位置一定指向下一个node
    //一旦链表构成环,则说明环开始的节点就是重复的数字(因为目前链表中的数字都是访问过的,再次访问说明出现重复值)
    //可以用快慢指针找到环开始的节点
    public int findDuplicate(int[] nums) {
        int slow = nums[0];//走一步
        int fast = nums[nums[0]];//走两步
        while(slow!=fast){
            slow = nums[slow];
            fast = nums[nums[fast]];
        }
        
        fast = 0;
        //设起点到交点长 m, 交点到快慢指针相遇长 s,环长r
        //则有到快慢指针相遇,慢指针走=m+s,快指针走2(m+s) = m+s+kr -> m = kr-s
        //快慢指针剩余 r-s 步能做到交点
        //当 r = 1, m = r-s
        while(fast!=slow){
            slow = nums[slow];
            fast = nums[fast];
        }
        
        return slow;
    }
}


猜你喜欢

转载自blog.csdn.net/iyangdi/article/details/78087274