Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
题目的意思就是给出一串整型数字,以及一个目标值,求这串数字中三个数字之和最接近目标值的情况,输出这个和。
思路:从中心向两侧扩展
这一题有点类似于LeetCode:15. 3Sum,只不过第15题是求出和为0的情况。我们还是使用相同的思路,从中心向两侧扩展。如果发现三个数字之和与目标值的差值小于0,则右侧数字向右移动,否则左侧数字向左移动。
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
sortNums = sorted(nums)
print(sortNums)
l = len(sortNums)
res = 0
minDx = 2147483647 # 最小差距
# 从中心向两边扩展
center = 1
toRightFlag = True # True:right+=1 ; False:left-=1
for center in range(l-1):
left = center -1
right = center + 1
while left >= 0 and right < l:
tmpSum = sortNums[left]+sortNums[center]+sortNums[right]
tmpDx = tmpSum - target
if tmpDx == 0:
if abs(tmpDx) < minDx:
print("=0",minDx,abs(tmpDx) , tmpSum)
minDx = abs(tmpDx)
res = tmpSum
if toRightFlag:
right = right + 1
else:
left = left -1
if tmpDx < 0:
if abs(tmpDx) < minDx:
print("<0",minDx,abs(tmpDx) , tmpSum)
minDx = abs(tmpDx)
res = tmpSum
right = right + 1
toRightFlag = True
if tmpDx > 0:
if abs(tmpDx) < minDx:
print(">0",minDx,abs(tmpDx) , tmpSum)
minDx = abs(tmpDx)
res = tmpSum
left = left -1
toRightFlag = False
return res
THE END.
博客围绕LeetCode 16. 3Sum Closest题目展开,题目要求给出一串整型数字和目标值,找出三个数字之和最接近目标值的情况并输出和。解题思路是从中心向两侧扩展,类似LeetCode 15. 3Sum,还给出了Python代码实现。
231

被折叠的 条评论
为什么被折叠?



