本文已参与「新人创作礼」活动,一起开启掘金创作之路。
原文链接:blog.csdn.net/roufoo/arti…
Closest Target Value Given an array, find two numbers in the array and their sum is closest to the target value but does not exceed the target value, return their sum. Example Input:target = 15 array = [1,3,5,11,7] Output:14 Notice if there is no result meet the requirement, return -1.
解法:双指针法
class Solution {
public:
/**
* @param target: the target
* @param array: an array
* @return: the closest value
*/
int closestTargetValue(int target, vector<int> &array) {
int len = array.size();
int p1 = 0, p2 = len - 1;
int maxV = INT_MIN;
sort(array.begin(), array.end());
if (array[0] > target) return -1;
while (p1 < p2) {
int sum = array[p1] + array[p2];
if (sum > target) p2--;
else {
p1++;
maxV = max(maxV, sum);
}
}
return maxV;
}
};