[LeetCode][python3]0016. 3Sum Closest

  1. My first try
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
N = len(nums)
nums.sort()
res = float('inf') # sum of 3 number
for t in range(N):
i, j = t + 1, N - 1
while i < j:
_sum = nums[t] + nums[i] + nums[j]
if abs(_sum - target) < abs(res - target):
res = _sum
if _sum > target:
j -= 1
elif _sum < target:
i += 1
else:
return target
return res
N2I -2020.03.21
  • abs(x) Absolute value of x
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
length = len(nums)
closest = []
for i, num in enumerate(nums[0:-2]):
l,r = i+1, length-1
# different with others' solution
if num+nums[r]+nums[r-1] < target:
closest.append(num+nums[r]+nums[r-1])
elif num+nums[l]+nums[l+1] > target:
closest.append(num+nums[l]+nums[l+1])
else:
while l < r:
sum = num+nums[l]+nums[r]
closest.append(sum)
if sum < target:
l += 1
elif sum > target:
r -= 1
else:
return target
closest.sort(key=lambda x:abs(x-target))
return closest[0]
N2I -2020.03.21
  • lambda x: somefunction(x) A small function that returns some function of the input x.

--

--

--

HI I’m N2I. Now a SWE in Taiwan. Check out more about me in https://nzi2020.blogspot.com/ or contact via email: nayzi9999@gmail.com

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Overlay using DecorView — PhoneWindow

How to automate Android App with Appium?

Mercurial: Devnet 2 Update!

FOHMO 4 Recap w/ DKD and Donmijoo

Get to Know How Golang is contributing to Bitly

You think you know, but you have no idea… or do you?

Minimum Remove to Make Valid Parentheses — Day 23(Python)

Day14, Better days

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
N2I

N2I

HI I’m N2I. Now a SWE in Taiwan. Check out more about me in https://nzi2020.blogspot.com/ or contact via email: nayzi9999@gmail.com

More from Medium

LeetCode Patterns Adventure 15 — Reverse Linked List

Merge Sort In Python

Basic Algorithms That You Need to Know by Heart to Crack Your Interviews

Heaps, the python way

heap