代码拉取完成,页面将自动刷新
package code;
import java.util.Arrays;
/*
* 16. 3Sum Closest
* 题意:找出3个数的和最接近target
* 难度:Medium
* 分类:Array, Two Pointers
* 思路:3sum的思路,每次记下最接近的res即可
* Tips:lc15, lc16, lc923
*/
public class lc16 {
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 start = i+1;
int end = nums.length-1;
while(start<end){
int sum = nums[i] + nums[start] + nums[end];
if(sum==target) return target;
else if(sum<target) start++;
else if(sum>target) end--;
if(Math.abs(sum-target)<Math.abs(res-target)) res = sum;
}
}
return res;
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。