<p style="box-sizing: border-box; margin-top: 0px; margin-bottom: 10px; color: rgb(51, 51, 51); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 14.3999996185303px; line-height: 30px;">题目:Given an array <span style="box-sizing: border-box;">S</span> of <span style="box-sizing: border-box;">n</span> integers, find three integers in <span style="box-sizing: border-box;">S</span> 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.</p><pre style="box-sizing: border-box; overflow: auto; font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; font-size: 13px; padding: 9.5px; margin-top: 0px; margin-bottom: 10px; line-height: 1.42857143; color: rgb(51, 51, 51); word-break: break-all; word-wrap: break-word; border: 1px solid rgb(204, 204, 204); border-radius: 4px; background-color: rgb(245, 245, 245);"> 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).
public class Solution {
public int threeSumClosest(int[] num, int target) {
int min=Integer.MAX_VALUE;
int result=0;//the sum of the three number
int len=num.length;
Arrays.sort(num);
for(int i=0;i<len-2;i++){
int start=i+1;
int end=len-1;
int sum=target-num[i];
while(start<end){
int sum1=num[start]+num[end];
int cur=Math.abs(sum1-sum);
if(cur<min){
min=cur;
result=num[start]+num[i]+num[end];
}
if(sum1<sum)start++;
if(sum1>sum)end--;
if(sum1==sum)return result;
}
}
return result;
}
}
这个题目和3sum的很相似,需要注意的问题:
两个变量:一个min存和target的差值,一个result存储三个数的和。
这里的技巧:
一个排好序的数组,找两个数的和的一定值,用while循环从两端找起,同时方便调整大小。(注意只有剩下两个数的和才方便调整大小三个以上的数要用for循环)这个四个数4sum的题目会更加有体现。