Problem: In a case where editing is not given array , an array of length n + 1 is found in any one of the duplicate numbers, all numbers within the range of 1 ~ n.
Length of the array, the array: input
Output: duplicate numbers
Ideas: Unable to modify the original array, face questions 3_1 algorithm ideas can not be used. The conditions of this question, must be a duplicate number, if an open array of size n, the original digital array into a new array table for position values, flower O (n) time complexity can find duplicate numbers. However, the space complexity is also O (n).
This article sacrifice time complexity for space complexity, similar dichotomy algorithm to find ideas are as follows:
Using the target properties of the array (index based on the elements corresponding positioning).
The numbers 1 ~ n (of length n + 1) is divided into two from the middle portion of the number m, the front half 1 ~ m, the back half of the m + 1 ~ n. If the number of digits exceeds 1 ~ m m, then it must contain half of the interval in duplicate numbers. In this case, the interval comprising repeating continues into two digits, until a duplicate numbers.
Code:
#include <iostream>
using namespace std;
int countRange(const int* numbers, int length, int start, int end);
int getDuplication(const int* numbers, int length)
{
if(numbers==nullptr || length<=0)
return -1;
int start = 1;
int end = length-1;
while(end >= start)
{
int middle = ((end - start)>>1)+start;
int count = countRange(numbers, length, start, middle);
if(end==start)
{
if(count> 1)
return start;
else
break;
}
if(count>(middle-start+1))
end =middle;
else
start=middle+1;
}
return -1;
}
int countRange(const int* numbers, int length, int start, int end)
{
if(numbers==nullptr)
return 0;
int count = 0;
for(int i=0; i<length; i++)
{
if(numbers[i]>=start&&numbers[i]<=end)
count+=1;
}
return count;
}
int main(int argc, char const *argv[])
{
int numbers[] = {0,3,2,1,3};
int result;
result = getDuplication(numbers,5);
if(result!=-1)
cout<<result<<endl;
else
cout<<"not found"<<endl;
return 0;
}
Complexity Analysis: time complexity of O (nlogn), the spatial complexity is O (1).
Expansion: the algorithm can not find all duplicate numbers.
For example, the array {2,3,5,7,4,3,2,6}, the numerical range of 1 to 2 occurs twice, the algorithm can not be determined once each occurrence 1 and 2, a digital still appeared 2 times.