287. find the number of repetitions
Given an n + 1 contains an integer array nums, which are digital (including 1 and n), found that the presence of at least one repeating integer between 1 to n. Assuming that only a unique integer, find the number of repeats.
Example 1:
Input: [1,3,4,2,2]
Output: 2
Example 2:
Input: [3,1,3,4,2]
Output: 3
Description:
You can not change the original array (assuming that the array is read-only).
Only use extra space O (1) is.
It is less than the time complexity of O (n2).
Only a duplicate array of numbers, but it may be repeated more than once.
PS:
speed thought pointer, a pointer is slow and FAST, nums [slow] represents the fetching pointer element corresponding
digital note nums array are between 1 to n (in the array will not walk out of range),
because there duplicate numbers, so this must be looped walk, inlet ring is repeated elements,
i.e. according to do to find the list of ideas inlet ring
class Solution {
public int findDuplicate(int[] nums) {
int fast = 0, slow = 0;
while(true) {
fast = nums[nums[fast]];
slow = nums[slow];
if(slow == fast) {
fast = 0;
while(nums[slow] != nums[fast]) {
fast = nums[fast];
slow = nums[slow];
}
return nums[slow];
}
}
}
}