題目:
解法:
- 先對(duì)數(shù)組從小到大排序。
- 最外層遍歷整個(gè)數(shù)組沥阱,再設(shè)置兩個(gè)雙指針缎罢,當(dāng)三數(shù)之和sum大于target時(shí)伊群,右指針向左移動(dòng)一位;當(dāng)三數(shù)之和sum小于target時(shí)策精,左指針向右移動(dòng)一位舰始。
- 設(shè)置一個(gè)diff是三數(shù)之和和target的差的絕對(duì)值,如果diff比當(dāng)前的mindiff小咽袜,則替換mindiff丸卷。
具體代碼如下:
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
res = 0
mindiff = 100000
for i in range(len(nums)):
left = i+1
right = len(nums)-1
while left<right:
sum = nums[left]+nums[right]+nums[i]
diff = abs(sum - target)
if diff < mindiff:
mindiff = diff
res = sum
if sum == target:
return sum
elif sum>target:
right -= 1
else:
left += 1
return res