leetcode. array .287 find the number of repetitions -Java

1. Specific topics

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.

2. Analysis of ideas

Since the subject of the request and can not change the original array with additional O (1) space, so "the arrangement of the array" or "array using HashSet storage elements" are not available.

Solution of the problem using the method of speed pointer: a pointer movement method is nextIndex = currValue, so that fast pointer moved two units each, a slow movement of the pointer unit. Due to the presence of repetitive elements in the array, it will form a ring, so that fast pointer always catch up with slow pointer. After the catch, you need to find the entrance of the ring. I is assumed that the array elements are repeated, then the entry is index = i, the position of the ring, find the inlet ring on the result obtained values.

3. Code

. 1   public  int findDuplicate ( int [] the nums) {
 2          IF (nums.length ==. 1) return the nums [0 ];
 . 3          // set the speed of the pointer, the pointer moves fast speed is slow pointer 2 times, the presence of a ring, fast the pointer in the pointer ring catch slow 
. 4          int sLOW the nums = [0], the nums FAST = [0 ];
 . 5          do {
 . 6              sLOW = the nums [sLOW];
 . 7              FAST = the nums [the nums [FAST]];
 . 8          } the while (SLOW =! FAST);
 . 9              
10          // find the entry loop 
. 11          SLOW the nums = [0 ];
 12 is         while(slow != fast){
13             slow = nums[slow];
14             fast = nums[fast];
15         }
16         return fast;
17     }

 

Guess you like

Origin www.cnblogs.com/XRH2019/p/11873919.html