Find duplicate numbers array

 

 Solution 1:

 

 Method 2: the speed of the pointer, ring

 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;
        while (fast != slow)
        {
            fast = nums[fast];
            slow = nums[slow];
        }
        return slow;
    }

    {3,1,2,0,2,5,3}

index   {0,1,2,3,4,5,6}

This is a ring: 3-> 0-> 3-> 0

{1,4,6,6,6,2,3}

1->4->6->3>6

A ring: Slow pointer, step by step, two-step two-step fast pointer, and so they are the same time, fast pointer back to the beginning, step by step, and so they are the same time, is that the duplicate numbers

Guess you like

Origin www.cnblogs.com/da-peng/p/11490421.html