Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
Subscribe to see which companies asked this question
思路:本题和3sum是同一个思路,只不过是对维护一个cloest而已,当一个子数组的和比cloest接近target时,把这个值赋给cloest,别的同3sum;
代码如下(已通过leetcode)
public class Solution {
public int threeSumClosest(int[] nums, int target) {
int length=nums.length;
if(nums==null &&length<3) return Integer.MIN_VALUE;
Arrays.sort(nums);
int ret=nums[0]+nums[1]+nums[2];
for(int i=0;i<length-2;i++) {
int j=i+1;
int k=length-1;
while(j<k) {
int sum=nums[i]+nums[j]+nums[k];
if(sum==target) return sum;
else {
if(Math.abs(sum-target)<Math.abs(ret-target)) {
ret=sum;
}
if(sum<target) {
j++;
} else {
k--;
}
}
}
}
return ret;
}
}