Skip to content

Commit 464c6ec

Browse files
committed
committed from zkp
1 parent 45a2fe8 commit 464c6ec

1 file changed

Lines changed: 33 additions & 0 deletions

File tree

LeetCode/threeSumClosest.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution:
2+
def threeSumClosest(self, nums, target):
3+
"""
4+
:type nums: List[int]
5+
:type target: int
6+
:rtype: int
7+
"""
8+
nums.sort()
9+
A = nums[0] + nums[1] + nums[2]
10+
gap = abs(A - target)
11+
for i in range(len(nums)):
12+
j = i + 1
13+
k = len(nums) - 1
14+
while j < k:
15+
s = nums[i] + nums[j] + nums[k] - target
16+
if s == 0:
17+
return target
18+
if gap > abs(s):
19+
gap = abs(s)
20+
A = s + target
21+
if s < 0:
22+
j += 1
23+
if j < k and nums[j] == nums[j-1]:
24+
j += 1
25+
elif s > 0:
26+
k -= 1
27+
if j < k and nums[k] == nums[k+1]:
28+
k -= 1
29+
return A
30+
31+
if __name__ == '__main__':
32+
a = Solution()
33+
print(a.threeSumClosest([1, -3, 3, 5, 4, 1], 1))

0 commit comments

Comments
 (0)