**
Leetcode P16 three sum closest @python Lang (LL)
**
Link: https://leetcode.com/problems/3sum-closest/
Content:
Method: two pointers (similar to 3 sum problem)
Algorithm:
- sort nums
- keeper: ans (store the smallest difference) initialized to None
- traverse, set a start i, left and right pointers, similar to three sum problem
- Judge abs(s-target) and abs(ans-target), if <, ans = s
and judge s ><= target at the same time to move pointers - return ans
Code:
def three_sum_closest(nums, target):
nums.sort()
ans = None
for i in range(len(nums)-2):
left = i+1
right = len(nums)-1
while left < right:
s = nums[i] + nums[left] + nums[right]
if ans == None or abs(s-target) < abs(ans-target):
ans = s
if s > target:
right -= 1
elif s < target:
left += 1
else:
return s
return ans
易出错得点: ans
Time complexity:
O(n2)