3Sum Closest
Question
None
Example 1
Input: nums = [-1, 2, 1, -4], target = 1
Output: 2
Solution
- ▭
- ▯
all//3Sum Closest.py
def three_sum_closest(nums, target):
nums.sort()
min_diff = float('inf')
res = float('inf')
for i in range(len(nums) - 2):
left = i + 1
right = len(nums) - 1
while left < right:
diff = nums[i] + nums[left] + nums[right] - target
if diff == 0:
return target
if abs(diff) < min_diff:
min_diff = abs(diff)
res = nums[i] + nums[left] + nums[right]
if diff < 0:
left += 1
else:
right -= 1
return res
nums = [-1, 2, 1, -4]
result = three_sum_closest(nums, 9999)
#print(result)
result |
---|
2 |
all//3Sum Closest.py
def three_sum_closest(nums, target):
nums.sort()
min_diff = float('inf')
res = float('inf')
for i in range(len(nums) - 2):
left = i + 1
right = len(nums) - 1
while left < right:
diff = nums[i] + nums[left] + nums[right] - target
if diff == 0:
return target
if abs(diff) < min_diff:
min_diff = abs(diff)
res = nums[i] + nums[left] + nums[right]
if diff < 0:
left += 1
else:
right -= 1
return res
nums = [-1, 2, 1, -4]
result = three_sum_closest(nums, 9999)
#print(result)
result |
---|
2 |