C++ 代码描述

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
#include<iostream>

using namespace std;

int checkFalseCoin(int begin,int end,int coins[]){
if((end-begin)==1){
return (coins[end]>coins[begin])?end:begin;
}
if((( end - begin + 1 ) & 1) == 0 ){
// 元素个数是双数
int leftSum = 0,rightSum = 0;
int middle = (end + begin + 1) / 2;
for(int i = begin ; i < middle ; i ++ ){
leftSum += coins[i];
}
for(int i = middle ; i <= end ; i ++ ){
rightSum += coins[i];
}
if( leftSum < rightSum){
return checkFalseCoin(middle,end,coins);
}else if(leftSum > rightSum){
return checkFalseCoin(begin,middle-1,coins);
}else{
return end;
}
}else{
// 元素个数是单数
int leftSum = 0,rightSum = 0;
int middle = (end + begin) / 2;
for(int i = begin ; i < middle ; i ++ ){
leftSum += coins[i];
}
for(int i = middle + 1 ; i <= end ; i ++ ){
rightSum += coins[i];
}
if( leftSum < rightSum){
return checkFalseCoin(middle,end,coins);
}else if(leftSum > rightSum){
return checkFalseCoin(begin,middle,coins);
}else{
return middle;
}
}
}

int main(){
int data[] = {1,1,1,1,1,2,1,1,1,1,1,1,1,1};
int n = 14;
std::cout << checkFalseCoin(0,n-1,data) << endl;
return 0;
}