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 1:
Input: nums = [-1,2,1,-4], target = 1
Output: 2
Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
Constraints:
3 <= nums.length <= 10^3
-10^3 <= nums[i] <= 10^3
-10^4 <= target <= 10^4
class Solution {
public int threeSumClosest(int[] nums, int target) {
int[] res = new int[3];
int dis = Integer.MAX_VALUE;
Arrays.sort(nums);
for(int i=0;i<nums.length-2;i++){
int j = i+1;
int l = nums.length-1;
int t = target - nums[i];
while(j<l){
//需要先判断,如果后判断将存在j==l的情况,此时不满足循环不变量
if(Math.abs(nums[j]+nums[l]-t)<dis){
res[0] = i;
res[1] = j;
res[2] = l;
dis = Math.abs(nums[j]+nums[l]-t);
}
//判断完两边指针再走
if(nums[j] + nums[l] == t){
return nums[i]+nums[j]+nums[l];
}else if(nums[j]+nums[l]<t){
j++;
}else{
l--;
}
}
}
return nums[res[0]] + nums[res[1]] + nums[res[2]];
}
}
原文:https://www.cnblogs.com/xm08030623/p/13518403.html