-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path3sum_closest.py
More file actions
34 lines (26 loc) · 764 Bytes
/
Copy path3sum_closest.py
File metadata and controls
34 lines (26 loc) · 764 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
27
28
29
30
31
32
33
34
class Solution:
# @return an integer
def threeSumClosest(self, num, target):
def abs(x):
if x > 0: return x
else: return -x
n = len(num)
num.sort()
min_gap = 999999
result = 999999
for i in xrange(n - 2):
j = i + 1
k = n - 1
while j < k:
sum = num[i] + num[j] + num[k]
gap = abs(target - sum)
if gap < min_gap:
min_gap = gap
result = sum
if sum < target:
j += 1
else:
k -= 1
return result
if __name__ == '__main__':
print Solution().threeSumClosest([-1, 2, 1, -4], 1)