1 Star 0 Fork 0

表情扭曲 / leetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
lc16.java 870 Bytes
一键复制 编辑 原始数据 按行查看 历史
liu13 提交于 2019-03-24 16:52 . 20190324
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;
}
}
1
https://gitee.com/abfantasy/leetcode.git
git@gitee.com:abfantasy/leetcode.git
abfantasy
leetcode
leetcode
master

搜索帮助