forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0016-3sum-closest.py
More file actions
26 lines (19 loc) · 857 Bytes
/
0016-3sum-closest.py
File metadata and controls
26 lines (19 loc) · 857 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
best = float('inf')
for i in range(len(nums) - 2):
val = nums[i]
left = i + 1
right = len(nums) - 1
while left < right:
currentGap = abs(target - (val + nums[left] + nums[right]))
if abs(best - target) > currentGap:
best = val + nums[left] + nums[right]
if val + nums[left] + nums[right] < target:
left += 1
elif val + nums[left] + nums[right] > target:
right -= 1
else: #closest it can get
return target
return best