題目
給你一個長度為 n 的整數(shù)數(shù)組 nums 和 一個目標值 target。請你從 nums 中選出三個整數(shù),使它們的和與 target 最接近。
返回這三個數(shù)的和。
假定每組輸入只存在恰好一個解。文章來源:http://www.zghlxwxcb.cn/news/detail-550209.html
思路
和三數(shù)之和那道題一樣,排序加雙指針文章來源地址http://www.zghlxwxcb.cn/news/detail-550209.html
Java代碼
class Solution {
public int threeSumClosest(int[] nums, int target) {
int res=1000000;
int m=0;
Arrays.sort(nums);
int left=0,right=0;
for(int i=0;i<nums.length;i++){
if(i>0&&nums[i]==nums[i-1]) continue;
left=i+1;right=nums.length-1;
while(left<right){
int result=nums[i]+nums[left]+nums[right];
if(result==target) return target;
if(Math.abs(result-target)<res){
res=Math.abs(result-target);
m=result;
}
if(result>target) right--;
else left++;
}
}
return m;
}
}
到了這里,關(guān)于2023/07/11_leetcode每日一題_16. 最接近的三數(shù)之和的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!