Given An array
nums containing
n + 1 integers where each integer is between 1 and
N (inclusi VE), prove that at least one duplicate 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.
Thinking Route:
1) After the sorting: do not meet the requirements of the condition 1, the array can not be changed;
2) Map: The space complexity of O (n) does not meet the requirements of condition 2.
Idea: for 2, think of the first Missing number of the solution, the array to save the original array information, and save the map information. Directly traversing the array nums,
Traversing to element I, Nums[i] is set to -1*nums[i], at this time nums[i] is negative, if the next time you traverse to I, you can check nums[i] is negative, you can know the number i is dumplicate number.
Misunderstanding: The process of writing, entered the misunderstanding, as long as the traversal encountered I, then will nums[i] set to -1*nums[i], after the traversal, if there is a negative number, that is, the corresponding subscript is
Number of dumplicate. This is because it is thought that it will only repeat two times, but the topic does not say that, if there are multiple occurrences (such as an even number of times), then it is possible to turn positive.
Code:
public class Solution {public int findduplicate (int[] nums) { int index, length = nums.length, result = 0; for (int i = 0; i < length; i++) { index = nums[i]; if (Index < 0) { index *=-1; } if (Nums[index] < 0) { result = index; break; } else { Nums[index] *=-1; } } return result;} }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Find the Duplicate number