[
two pointers
sort
2sum
]
BinarySearch 0369 Sum of Three Numbers Sequel
Problem statement
https://binarysearch.com/problems/Sum-of-Three-Numbers-Sequel/
Solution
Equal to Leetcode 0016 3Sum Closest.
Complexity
It is O(n^2)
for time and O(1)
for space.
Code
class Solution:
def solve(self, nums, target):
nums.sort()
n, ans = len(nums), float("inf")
for i in range(n):
beg, end = i + 1, n - 1
while beg < end:
sm = nums[beg] + nums[end] + nums[i]
ans = min(ans, sm, key = lambda x: abs(x - target))
if sm <= target:
beg += 1
elif sm > target:
end -= 1
return abs(ans - target)