method: 2 pointers => leetcode 15 -> 16
1 prepare a res = infinity
2 sort the array
3 for each i in loop, use 2 pointers to find the closest
4 if equals to target, return target
5 else return closest
6 if low >= high, output res
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
res = float('inf')
nums.sort()
for i in range(len(nums)):
lo, hi = i + 1, len(nums) - 1
while lo < hi:
three = nums[i] + nums[lo] + nums[hi]
if three == target:
return target
if abs(three - target) < abs(res - target):
res = three
if three < target:
lo += 1
else:
hi -= 1
return res
method: 补充一句话加快速度
if i > 0 and nums[i] == nums[i-1]:
continue
因为已经遍历过的元素没有必要再次遍历,再次遍历是的结果一定是他的子集
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
res = float('inf')
nums.sort()
for i in range(len(nums)):
if i > 0 and nums[i] == nums[i-1]:
continue
lo, hi = i + 1, len(nums) - 1
while lo < hi:
three = nums[i] + nums[lo] + nums[hi]
if three == target:
return target
if abs(three - target) < abs(res - target):
res = three
if three < target:
lo += 1
else:
hi -= 1
return res