腾讯五十题No.10 最接近的三数之和
class Solution {
public int threeSumClosest(int[] nums, int target) {
int res = Integer.MAX_VALUE;
Arrays.sort(nums);
int sum = 0;
for(int i = 0;i<nums.length;i++){
if(i>0 && nums[i] == nums[i-1]) continue;
int l = i+1,r = nums.length - 1;
while(l<r){
sum = nums[i] + nums[l] + nums[r];
if(sum == target){
res = sum;
}else if(Math.abs(target - sum) < Math.abs(target - res)){
res = sum;
}else{
while(l<r && nums[l] == nums[l+1]) l++;
while(l<r && nums[r] == nums[r-1]) r--;
}
l++;
r--;
}
}
return res;
}
}
应该把差值定义成 Math.MAX_VALUE
class Solution {
public int threeSumClosest(int[] nums, int target) {
Arrays.sort(nums);
int res = 0;
int diff = Integer.MAX_VALUE;
for(int i = 0; i < nums.length-2; ++i){
int j = i+1, k = nums.length-1;
while(j < k){
int sum = nums[i] + nums[j] + nums[k];
if(sum == target) return sum;
if(Math.abs(sum-target) < diff){
diff = Math.abs(sum-target);
res = sum;
}
if(sum < target)
j++;
else if(sum > target)
k--;
}
}
return res;
}
}
本文来自博客园,作者:蹇爱黄,转载请注明原文链接:https://www.cnblogs.com/jianjiana/p/15864972.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?