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

思路:

也想出一个方法,O(n)时间复杂度,O(1)的空间复杂度的,但是要修改数组的值,很遗憾这是不符合条件的。大概思路为假设所有的数字为1~n之间的数字且都不相同,最后肯定可以让每个元素num都放在index为(num-1)的位置,如果有一个数字出现了不止一次呢,肯定就不是所有的位置index所对应的元素的值为(index+1)了,就从这里入手。index位置的元素为num1,nums[num1-1]位置的数为num2,如果num1和num2都不在它应该在的index-1的位置,则交换两个位置的值,否则,判断下一个元素;交换元素后呢,则从交换元素后的下一个更小的位置执行,即num1或num2中index的值比较小的位置开始再判断,只到所有的元素被遍历一遍。

看了下题解,网上有用快慢指针解决该问题的方法,还有一个基于二分查找的方法,脑子比较累了,暂时想不通,先挖个坑,改天再填。

代码:

个人见解:

public  int findDuplicate(int[] nums) {
		int temp = 0;
		int i = 0,index=0;
		while (i < nums.length) {
			if (i + 1 != nums[i]) {
				index=nums[i]-1;
				if(nums[index]!=nums[i])
					swap(nums, i, index);
				else {
					i++;
				}
				//i = nums[i] - 1;
			} else
				i++;

		}
		for (i = 0; i < nums.length; i++) {
			if (i + 1 != nums[i]) {
				temp = nums[i];
				break;
			}
		}
		return temp;
	}

	public void swap(int[] nums, int index1, int index2) {
		int temp = nums[index1];
		nums[index1] = nums[index2];
		nums[index2] = temp;
	}

二分查找的方法:

At first the search space is numbers between 1 to n. Each time I select a number mid (which is the one in the middle) and count all the numbers equal to or less than mid. Then if the count is more than mid, the search space will be [1 mid] otherwise [mid+1 n]. I do this until search space is only one number.

Let's say n=10 and I select mid=5. Then I count all the numbers in the array which are less than equal mid. If the there are more than 5 numbers that are less than 5, then by Pigeonhole Principle (https://en.wikipedia.org/wiki/Pigeonhole_principle) one of them has occurred more than once. So I shrink the search space from [1 10] to [1 5]. Otherwise the duplicate number is in the second half so for the next step the search space would be [6 10].

public class Solution {
public int findDuplicate(int[] nums) {
    int n=nums.length-1;
    int left=0, right=n; 
    while(left<right){
        int mid=left+(right-left)/2;
        int count=numBelow(nums, mid);
        if(count>mid) right=mid;
        else left=mid+1;
    }
    return left;
}
public int numBelow(int[] nums, int target){
    int result=0;
    for(int i=0; i<nums.length; i++)
        if(nums[i]<=target) result++;
    return result;
  }
}

另外一种用快慢指针来解决的:

The main idea is the same with problem Linked List Cycle II,https://leetcode.com/problems/linked-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;
}
证明:

  1. Suppose there is "m" steps from nums[0] to entry point, and the length of circle is "n" steps.

  2. When slow arrives entry point after m steps, the fast has advanced (2m+1) steps

    slow = m

    fast = 2m+1

  3. The distance from slow to fast in the circle is:

    D = (C*n + slow) - fast

    = C*n - (m + 1)

    where C = ceil(m/n)

  4. Since fast needs D steps to catch up with slow, the distance from meet point to entry point is D as well.

  5. After (m+1) steps, slow would be sure at the entry point:

    D1 = D + (m+1) = C*n

  6. At the second loop, fast should start from 0 rather than num[0], so that it would arrive entry point after (m+1) steps.


你可能感兴趣的:(leetcoce_Find the Duplicate Number)