您的位置:首页 > 其它

数组重复数字 不修改数组

2018-03-11 22:15 148 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: