-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3sum_closet.py
More file actions
32 lines (25 loc) · 875 Bytes
/
3sum_closet.py
File metadata and controls
32 lines (25 loc) · 875 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
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
n = len(nums)
closest_sum = float('inf')
for i in range(n - 2):
left, right = i + 1, n - 1
while left < right:
current_sum = nums[i] + nums[left] + nums[right]
# Update closest sum if needed
if abs(target - current_sum) < abs(target - closest_sum):
closest_sum = current_sum
# Move pointers
if current_sum < target:
left += 1
elif current_sum > target:
right -= 1
else:
return current_sum # Perfect match found
return closest_sum