Leetcode——Array 3

来源:互联网 发布:手机逛淘宝费流量吗 编辑:程序博客网 时间:2024/06/10 14:27

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:
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.

思路:
该题和Array 2 最大的不同点在于不能在原来的数组上进行修改,于是第一反应是回归原思路,创建一个相同的数组,然后排序,判断临近位相等的位置。今天看到大神做法,因为存在一个重复的数字,所以从链表的角度来看的话,部分节点会形成一个闭合,因此创建一个慢指针,一个快指针,慢指针 slow = nums[slow]; fast = nums[nums[fast]];两个指针会在circle相遇。之后的另一个while循环不知理解是否正确,因为第一个循环里面fast走了2*path和慢指针的path相遇,因此第二个循环里慢指针再走path将和从头开始的指针相遇。(这样解释会觉得两个path是一样的,这是因为起点不同nums[0] vs 0?)

大神代码实现如下:

public class Solution {    public int findDuplicate(int[] nums) {        int slow = nums[0];        int fast = nums[nums[0]];        while(fast != slow){            slow = nums[slow];            fast = nums[nums[fast]];        }        fast = 0;        while(fast != slow){ // still don't get why they will definitely meet            slow = nums[slow];            fast = nums[fast];        }        return slow;    }}
0 0
原创粉丝点击