Given an array
nums
of n integers and an integer target
, find three integers in nums
such that the sum is closest to target
. Return the sum of the three integers. You may assume that each input would have exactly one solution.Example:
Given array nums = [-1, 2, 1, -4], and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
class Solution {
public:
int threeSumClosest(vector<int>& a, int target) {
const int n = a.size();
int res = ;
if (n < ) {
for (auto& ii :a){
res+=ii;
}
return res;
}
std::sort(a.begin(),a.end());
res = a[] + a[] + a[];
for(int i = ; i < n-; ++i) {
int low = i + ;
int high = n - ;
while(low < high) {
int cur_sum = a[i] + a[low] + a[high];
if (abs(cur_sum - target) < abs(res - target)) {
res = cur_sum;
};
if (cur_sum > target) {
high--;
} else if (cur_sum < target) {
low++;
} else {
return target;
}
}
}
return res; }
};
class Solution {
public int threeSumClosest(int[] nums, int target) {
int res = nums[0]+nums[1]+nums[2];
Arrays.sort(nums);
for(int i = 0 ; i<nums.length-2;i++){
int lo=i+1,hi=nums.length-1;
while(lo<hi){
int sum=nums[i]+nums[lo]+nums[hi];
if(sum>target) hi--;
else lo++;
if(Math.abs(sum-target)<Math.abs(res-target))
res = sum;
}
}
return res;
}
}