給你一個長度為 n 的整數(shù)數(shù)組 nums 和 一個目標值 target。請你從 nums 中選出三個整數(shù),使它們的和與 target 最接近。
返回這三個數(shù)的和。
假定每組輸入只存在恰好一個解。
示例 1:輸入:nums = [-1,2,1,-4], target = 1
輸出:2
解釋:與 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
輸入:nums = [0,0,0], target = 1
輸出:0
與上一題思路相同,固定第一個數(shù),移后兩個數(shù),雙指針,比目標值大,右指針左移,比目標值小,左指針右移,直到left大于等于right。
java版class Solution {public int threeSumClosest(int[] nums, int target) {Arrays.sort(nums);
int ans = nums[0] + nums[1] + nums[2];
for(int i=0;iint start = i+1, end = nums.length - 1;
while(start< end) {int sum = nums[start] + nums[end] + nums[i];
if(Math.abs(target - sum)< Math.abs(target - ans))
ans = sum;
if(sum >target)
end--;
else if(sum< target)
start++;
else
return ans;
}
}
return ans;
}
}
你是否還在尋找穩(wěn)定的海外服務器提供商?創(chuàng)新互聯(lián)www.cdcxhl.cn海外機房具備T級流量清洗系統(tǒng)配攻擊溯源,準確流量調(diào)度確保服務器高可用性,企業(yè)級服務器適合批量采購,新人活動首月15元起,快前往官網(wǎng)查看詳情吧