-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path3_sum_losest.py
More file actions
24 lines (22 loc) · 906 Bytes
/
3_sum_losest.py
File metadata and controls
24 lines (22 loc) · 906 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
from typing import List
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
rev = [target - num for num in nums]
min_gap = 10 ** 5
total = 0
for pos in range(0, len(nums) - 2):
if nums[pos] == nums[pos - 1] and pos - 1 >= 0:
continue
start, end = pos + 1, len(nums) - 1
while pos < start < end < len(nums):
if min_gap > abs(rev[pos] - nums[start] - nums[end]):
min_gap = abs(rev[pos] - nums[start] - nums[end])
total = nums[start] + nums[end] - rev[pos] + target
if nums[start] + nums[end] < rev[pos]:
start += 1
elif nums[start] + nums[end] > rev[pos]:
end -= 1
else:
return target
return total