-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoffer_3
59 lines (50 loc) · 1.08 KB
/
offer_3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//题目1
bool duplicate(int numbers[],int length,int* duplication)
{
if(numbers == nullptr || length<=0) return false;
for(int i=0; i<length ;++i){
if(numbers[i]<0 || num[i]>length-1) return false;
}
for(int i=0;;i<length;++i){
while(i != numbers[i]){
if(numbers[i] == numbers[numbers[i]]){
*duplication = numbers[i];
return true;
}
int temp=numbers[i];
number[i]=numbers[temp];
numbers[temp] = temp;
}
return false;
}
}
//题目2
int getDuplication(const int* numbers[],int length)
{
if(numbers == nullptr || length<=0) return false;
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(int* numbers,int length,int start,int middle)
{
if(numbers == nullptr) return 0;
int count=0;
for(int i=0;i<length;++i){
if(numbers[i]>=start && numbers[i]<=middle)
++count;
}
return count;
}