1 题目理解
昨晚上光顾着吃深夜泡面,忘了更新了。。所以这一更就算是补上昨天的,今天的另算。
这道题和 Leetcode #15 3Sum 三数之和 解题小节 很像,区别是#15是要三数之和等于目标值,这题是最接近就可以
做法其实都一样,大家可以点进去看,
也是选择一个基准,然后设立头部和尾巴,向中间靠拢
唯一的不同就是:时刻判断是否出现最接近值!
2 原题
3Sum Closest
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).
3 AC解
我是复制上一题的代码。。哈哈
public class Solution {
/**
* 其实就是直接复制上一题了
* */
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int i,j,k,result=0,reserve;
int min=Integer.MAX_VALUE;
for(i=0;i<nums.length-2;i++){
j=i+1;
k=nums.length-1;
reserve=target-nums[i];
while(j<k){
if(Math.abs(reserve-nums[j]-nums[k])<min){
result=nums[i]+nums[j]+nums[k];
min=Math.abs(reserve-nums[j]-nums[k]);
}
if(nums[j]+nums[k]<reserve){
j++;
} else{
k--;
}
}
}
return result;
}
}