(Medium #16) 3Sum Closest
Problem
Given an array
nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
My solution
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
closet = [nums[0], nums[1], nums[-1]]
for i in range(len(nums)-2):
choice_1 = nums[i]
if i> 0 and choice_1 == nums[i-1]:
continue
start = i+1
end = len(nums)-1
while start < end:
choice_2 = nums[start]
choice_3 = nums[end]
if choice_1+choice_2+choice_3-target < 0:
while start < end and nums[start] == nums[start+1]:
start += 1
start += 1
if abs(choice_1+choice_2+choice_3-target) < abs(sum(closet)-target):
closet = [choice_1, choice_2, choice_3]
elif choice_1+choice_2+choice_3-target > 0:
while start < end and nums[end] == nums[end-1]:
end -= 1
end -= 1
if abs(choice_1+choice_2+choice_3-target) < abs(sum(closet)-target):
closet = [choice_1, choice_2, choice_3]
else: # choice_1 + choice_2 + choice_3 == target:
closet = [choice_1, choice_2, choice_3]
return sum(closet)
return sum(closet)
Runtime: 136ms, Memory: 13.8MBdef threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
closet = [nums[0], nums[1], nums[-1]]
for i in range(len(nums)-2):
choice_1 = nums[i]
if i> 0 and choice_1 == nums[i-1]:
continue
start = i+1
end = len(nums)-1
while start < end:
choice_2 = nums[start]
choice_3 = nums[end]
if choice_1+choice_2+choice_3-target < 0:
while start < end and nums[start] == nums[start+1]:
start += 1
start += 1
if abs(choice_1+choice_2+choice_3-target) < abs(sum(closet)-target):
closet = [choice_1, choice_2, choice_3]
elif choice_1+choice_2+choice_3-target > 0:
while start < end and nums[end] == nums[end-1]:
end -= 1
end -= 1
if abs(choice_1+choice_2+choice_3-target) < abs(sum(closet)-target):
closet = [choice_1, choice_2, choice_3]
else: # choice_1 + choice_2 + choice_3 == target:
closet = [choice_1, choice_2, choice_3]
return sum(closet)
return sum(closet)
댓글
댓글 쓰기