[LeetCode][python3]0016. 3Sum Closest

Start the Journey
N2I -2020.03.21

1. My first try

  1. class Solution:
  2. def threeSumClosest(self, nums: List[int], target: int) -> int:
  3. N = len(nums)
  4. nums.sort()
  5. res = float('inf') # sum of 3 number
  6. for t in range(N):
  7. i, j = t + 1, N - 1
  8. while i < j:
  9. _sum = nums[t] + nums[i] + nums[j]
  10. if abs(_sum - target) < abs(res - target):
  11. res = _sum
  12. if _sum > target:
  13. j -= 1
  14. elif _sum < target:
  15. i += 1
  16. else:
  17. return target
  18. return res

Note:

  • abs(x) Absolute value of x

Explanation:

Using absolute value to determine the distance between sum and target. Return the smallest one.


2. A better solution

  1. class Solution:
  2. def threeSumClosest(self, nums: List[int], target: int) -> int:
  3. nums.sort()
  4. length = len(nums)
  5. closest = []
  6. for i, num in enumerate(nums[0:-2]):
  7. l,r = i+1, length-1
  8. # different with others' solution
  9. if num+nums[r]+nums[r-1] < target:
  10. closest.append(num+nums[r]+nums[r-1])
  11. elif num+nums[l]+nums[l+1] > target:
  12. closest.append(num+nums[l]+nums[l+1])
  13. else:
  14. while l < r:
  15. sum = num+nums[l]+nums[r]
  16. closest.append(sum)
  17. if sum < target:
  18. l += 1
  19. elif sum > target:
  20. r -= 1
  21. else:
  22. return target
  23. closest.sort(key=lambda x:abs(x-target))
  24. return closest[0]

Note:

  • lambda x: somefunction(x) A small function that returns some function of the input x.

Explanation:

It reduces the searching time if num+nums[r]+nums[r-1]<target or num+nums[l]+nums[l+1]>target, and save all sum in closest and determine the shortest distance in the end.