Original title URL: https://leetcode.com/problems/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 D Uplicate number must exist. Assume that there are only one duplicate number, find the duplicate one.
Note:
You must the Modify the array (assume the array was read only). You must use only constant, O (1) Extra space. Your runtime complexity should is less than O (N2). There is a duplicate number in the array, but it could was repeated more than once.
Method One: Apply the pigeon cage principle to find the binary method.
Because you can place up to n different numbers in the range of 1~n, the array now has n+1 numbers, so there is at least one repetition.
For a number m in the 1~n range, the number of the array that is less than or equal to M is at least m, and when it is just M, there is no repetition between the 1~m. We separate to prove.
public class Solution {public
int findduplicate (int[] nums) {
int. = 1, high = nums.length-1;
while (Low
Method Two: Cyclic chain detection method. This method I did not think out, found on the Internet, the use of technology and the circular link list detection method exactly the same.
public class Solution {public
int findduplicate (int[] nums) {
int slow = 0, fast = 0;
Do {
slow = Nums[slow];
Fast = Nums[nums[fast]];
} while (Nums[slow]! = Nums[fast]);
int restart = 0;
while (Nums[restart]! = Nums[slow]) {
restart = Nums[restart];
slow = Nums[slow];
}
return Nums[restart];
}
}
Reference article:
http://bookshadow.com/weblog/2015/09/28/leetcode-find-duplicate-number/
https://segmentfault.com/a/1190000003817671