3-2 face questions: array is not modified to identify duplicate numbers

The title and 3-1 is basically the same, except that the array can not be changed, the auxiliary array can be considered to solve solution 3-1, to solve the cost of space.

1. Title Description

In an array of length n + 1, where all numbers are in the range of 1 ~ n, so there is at least one number in the array is repeated. Please find an array of any one of the duplicate numbers, but can not modify the input array. 8, for example, the length of the input array {2,3,5,4,3,2,6,7}, then the corresponding output is repeatable number 2 or 3.

2. Different Solution

Similar considerations binary search to search for values ​​within the range of 1 ~ n is two points if the number of elements in an array within a defined range of values ​​greater than the range, then there must be in this range is repeated numbers.

The {1,2,4,3,3}, consider taking half the range of 1 to 5 1 to 3, the number of elements within the statistical range of 4, indicating that there are duplicate elements 1 to 3, and then divided by two.

 1     public static int getRepeatNumber(int[] array) {
 2         // Judge the boundary of this problem
 3         int len = array.length;
 4         if (len == 0) {return -1;}
 5         int lo = 1;
 6         int hi = len - 1;
 7         while(lo <= hi) {
 8             int mid = (hi + lo) / 2;
 9             int count = 0;
10             for (int n:
11                  array) {
12                 if (n >= lo && n <= mid) {
13                     count++;
14                 }
15             }
16             if (hi == lo) {
17                 if (count > 1) {
18                     return hi;
19                 } else {
20                     break;
21                 }
22             }
23             if (count > mid - lo + 1) {
24                 hi = mid;
25             } else {
26                 lo = mid + 1;
27             }
28         }
29         return -1;
30     }

Complexity Analysis: time complexity of O (nlogn), the spatial complexity is O (1).

Guess you like

Origin www.cnblogs.com/zxzhou/p/11695289.html