forked from JediXL/LeetCodeByPython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path16 3SumClosest.py
40 lines (37 loc) · 1.21 KB
/
16 3SumClosest.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
#!/usr/bin/env python
# coding=utf-8
class Solution:
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
# 如果只有3个数,那直接返回这三个数的和
if len(nums) == 3:
return sum(nums)
nums = sorted(nums)
# 如果最小的和大于目标,那返回最小的和
if sum(nums[:3]) >= target:
return sum(nums[:3])
# 如果最大的和小于目标,那返回最大的和
if sum(nums[-3:]) <= target:
return sum(nums[-3:])
cur = nums[0] + nums[1] + nums[-1]
for i in range(0, len(nums) - 2):
# 避免重复计算
if i > 0 and nums[i] == nums[i - 1]:
continue
j = i + 1
k = len(nums) - 1
while j < k:
res = nums[i] + nums[j] + nums[k]
if abs(res - target) < abs(cur - target):
cur = res
elif res == target:
return target
elif res < target:
j = j + 1
else:
k = k - 1
return cur