-
Notifications
You must be signed in to change notification settings - Fork 0
/
16.py
40 lines (37 loc) · 1.18 KB
/
16.py
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from collections import Counter
class Solution:
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
# Any more than 3 occurrences of an int do not affect the solution
counts = Counter(nums)
nums = []
for element in counts:
nums += [element] * min(3, counts[element])
nums.sort()
t_neg_c = [target-element for element in nums]
# a + b + c = target
# a + b = target - c
dist = float('inf')
best = None
for i in range(len(t_neg_c)):
tc = t_neg_c[i]
search = nums[:i] + nums[i+1:]
left = 0
right = len(search) - 1
while left < right:
ab = search[left] + search[right]
current_dist = ab - tc
if abs(current_dist) < dist:
dist = abs(current_dist)
best = ab + nums[i]
if current_dist > 0:
right -= 1
elif current_dist < 0:
left += 1
else:
break
return best