[
two pointers
2sum
sort
]
BinarySearch 0280 Sum of Three Numbers
Problem statement
https://binarysearch.com/problems/Sum-of-Three-Numbers/
Solution
Variation of Leetcode 0015. 3Sum
Complexity
It is O(n^2)
for time and O(n)
for space.
Code
class Solution:
def solve(self, nums, k):
nums.sort()
n, result = len(nums), []
for i in range(n):
if i > 0 and nums[i] == nums[i-1]: continue
target = k - nums[i]
beg, end = i + 1, n - 1
while beg < end:
if nums[beg] + nums[end] < target:
beg += 1
elif nums[beg] + nums[end] > target:
end -= 1
else:
return True
beg += 1
end -= 1
return False