287. Find the Duplicate Number

来源:互联网 发布:pp助手软件源 编辑:程序博客网 时间:2024/04/29 09:54

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.


注意这题的条件,有一个条件就是n+1个整数的范围是1~n,这个暗示比较明显了,再加上要求的只能额外常数空间要求,联想到前面做过的题,

尝试把数字放到相应的index上面去,n+1个数,数组的最大下标刚好是n,多出来的一个index=0刚好可以选做一个开始的位置。

随便选数组中的数(从第一个开始好了),例如第一个数为4,就把4换到index=4的位置,原来index=4的位置的数做同样的操作,如此迭代下去,这样直到【将要】换但是index已经等于【将要】换的数字的时候,这个重复的数字就找到了(题目保证重复数字存在)。

 public static int findDuplicate(int[] nums){int len=nums.length;int index=0;while(nums[index]!=index){int temp=nums[index];nums[index]=index;index=temp;}return index;}



上面的解法修改了数组,不满足数组是只读的条件,满足条件的解法

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



The main idea is the same with problem Linked List Cycle II,List Cycle II ,Use two pointers the fast and the slow. The fast one goes forward two steps each time, while the slow one goes only step each time. They must meet the same item when slow==fast. In fact, they meet in a circle, the duplicate number must be the entry point of the circle when visiting the array from nums[0]. Next we just need to find the entry point. We use a point(we can use the fast one before) to visit form begining with one step each time, do the same job to slow. When fast==slow, they meet at the entry point of the circle. The easy understood code is as follows.

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;}

0 0