#include <iostream>
#include <cstdlib>
#include <stdio.h>
//数组长度n+1,内容为1到n的数字,有重复
//二分法 数组中重复数字 不能修改数组内容 时间复杂度O(nlogn) 空间复杂度O(1)
int count(int* numbers,int length,int start,int end);
int getDuplication(int* numbers, int length){
if(length <= 0 || numbers == nullptr)
return -1; //i make mistake here for using return false as return 0;
int start=1,end=length;
int i=0;
while(end>=start){
int middle=start+((end - start) >> 1); //i make mistake here with +1
int range = count(numbers,length,start,middle);
if(end == start){
if(range){
return start;
}
else
return -1;
}
if(range){
end = middle;
}
else
start = middle +1;
}
}
int count(int* numbers,int length,int start,int end){
if(numbers == nullptr || end < start)
return false;
int countrange=0;
for(int i=0;i<length;i++){
if(numbers[i]>=start && numbers[i]<=end){
countrange++;
}
}
if(countrange > (end-start+1))
return 1;
else
return 0;
}
数组重复数字 不修改数组
最新推荐文章于 2019-10-22 11:38:40 发布