-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy path16.3sum-closest.py
58 lines (44 loc) · 1.76 KB
/
16.3sum-closest.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
res = float('inf')
nums.sort()
for i in range(len(nums) - 2):
a = nums[i]
left = i + 1
right = len(nums) - 1
while left < right:
threeSum = a + nums[left] + nums[right]
if abs(threeSum - target) < abs(res - target):
res = threeSum
if threeSum == target:
break
elif threeSum > target:
right -= 1
else:
left += 1
return res
class Solution2:
def threeSumClosest(self, nums: List[int], target: int) -> int:
closest = float('inf')
nums.sort()
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
a = nums[i]
left = i + 1
right = len(nums) - 1
while left < right:
threeSum = a + nums[left] + nums[right]
if abs(threeSum - target) < abs(closest - target):
closest = threeSum
if threeSum == target:
break
elif threeSum > target:
while (left < right and nums[right] == nums[right - 1]): #remove duplicate
right -= 1
right -= 1
else:
while (left < right and nums[left] == nums[left + 1]): #remove duplicate
left += 1
left += 1
return closest