#define SIZE 10
int cloest = INT_MAX;
void judgeAndPut(int* arr, int fix, int begin, int end, int target) {
while (begin < end) {
int cur = arr[fix] + arr[begin] + arr[end];
if (abs(cur - target) < abs(cloest - target)) {
cloest = cur;
}
if (cur < target) {
begin++;
while (begin < end && arr[begin] == arr[begin - 1]) {
begin++;
}
} else {
end--;
while (begin < end && arr[end] == arr[end + 1]) {
end--;
}
}
}
}
int findCloest(int* arr, int target) {
qsort(arr, SIZE, sizeof(int), myCmp);
for (int i = 0; i < SIZE; i++) {
cout << " " << arr[i];
}
cout << endl;
for (int i = 0; i < SIZE - 2; ++i) {
if (cloest == target) {
break;
}
if (i != 0 && arr[i] == arr[i - 1]) {
continue;
}
judgeAndPut(arr, i, i + 1, SIZE - 1, target);
}
return cloest;
}
最接近目标的三数和
最新推荐文章于 2022-11-27 21:59:40 发布