-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0016-3sum-closest.py
More file actions
28 lines (24 loc) · 762 Bytes
/
0016-3sum-closest.py
File metadata and controls
28 lines (24 loc) · 762 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
# time complexity: O(n^2)
# space complexity: O(nlogn)
from typing import List
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
diff = float('inf')
nums.sort()
for i in range(len(nums)):
left = i + 1
right = len(nums) - 1
while left < right:
sum = nums[i] + nums[left] + nums[right]
if abs(target - sum) < abs(diff):
diff = target - sum
if sum < target:
left += 1
else:
right -= 1
if diff == 0:
break
return target - diff
nums = [-1, 2, 1, -4]
target = 1
print(Solution().threeSumClosest(nums, target))