16. 3Sum Closest
https://leetcode.com/problems/3sum-closest/
Input: nums = [-1,2,1,-4], target = 1
Output: 2
Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).Thoughts
Code
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
diff, res = math.inf, 0
for i, num in enumerate(nums):
l, r = 0, i - 1
while l < r:
s = sum((nums[l], nums[r], num))
if s < target:
l += 1
elif s > target:
r -= 1
else:
return s
if abs(s - target) < diff:
diff = abs(s - target)
res = s
return res
Analysis
Last updated