Interview Question 3 (b): Do not modify the array to find duplicate numbers
Title: All numbers in an array of length n+1 are within the range of 1 to N, so the array
A few numbers are duplicated. Please find any duplicate numbers in the array, but you cannot modify the input
Array. For example, if you enter an array of length 8 {2, 3, 5, 4, 3, 2, 6, 7}, then the corresponding
The output is a repeating number 2 or 3.
Problem Solving Ideas:
You cannot modify an array, you can create a secondary array of length n+1, and the space complexity is O (n).
If you use time to change space, you can use the idea of two-point search.
The element range is 1~n, but there are n+1 elements that indicate that a number has been duplicated.
The median number m is divided into two parts, 1~m and M+1~n.
If the number of elements in the 1~m exceeds m, the repeating element is divided in the first half, again 1~m.
Repeat this process until you finally find the duplicate element.
Pseudo code:
if(Invalid input parameter)return-1;
intstart=1;intend=length-1; while(start<=end) { intmiddle=interval midpoint; intCount=the number of elements between start and middle; if(the upper and lower bounds of the interval are equal) {if(count greater than 1)returnstart; Else return-1; } if(Count> (middle-start+1)) End=Middle; ElseStart=middle+1;}return-1;
C + + code:
intGetduplication (Const int* Numbers,intlength) { //Verifying the validity of input parameters if(numbers==nullptr| | length<0){ return-1; } for(intI=0; i<length;i++){ if(numbers[i]<1|| numbers[i]>length-1){ return-1; } } //finding duplicate elements in two points intstart=1; intend=length-1; while(end>=start) { intMiddle= (End-start) >>1)+start; intCount=Countrange (Numbers,length,start,middle); //the upper and lower bounds of the interval are equal if(end==start) { //the number of elements is greater than 1, successful lookups if(count>1) returnstart; Else Break; } //range Upper and lower bounds, continuation of binary search if(Count> (middle-start+1)) End=Middle; ElseStart=middle+1; } return-1;}//get the number of interval elementsintCountrange (Const int* Numbers,intLengthintStartintmiddle) { if(numbers==nullptr| | length<0){ return-1; } intCount=0; for(intI=0; i<length;i++){ if(numbers[i]>=start&&numbers[i]<=middle) Count++; } returncount;}
Resources:
Sword point 3 (b)
Interview Question 3 (b): Do not modify the array to find duplicate numbers