-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path16.py
56 lines (43 loc) · 1.3 KB
/
16.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
class Solution(object):
def hehe(self,i):
left = i+1
right = len(self.nums)-1
mmin = abs(self.nums[i] + self.nums[left] + self.nums[right] - self.target)
wds = self.nums[i] + self.nums[left] + self.nums[right]
while left != right:
he = self.nums[i] + self.nums[left] + self.nums[right]
ca = abs(he - self.target)
if ca == 0:
return he
if mmin > ca:
wds = he
mmin = ca
if he > self.target:
right -= 1
continue
if he < self.target:
left += 1
continue
return 0
return wds
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
self.target= target
self.nums = sorted(nums)
mmin = 2147483647
wds = 214746323
for i in range(len(nums)-2):
hh = self.hehe(i)
if hh == self.target:
return target
if abs(hh-self.target) < mmin:
mmin = abs(hh-self.target)
wds = hh
return wds
if __name__ == '__main__':
wds = Solution()
print wds.threeSumClosest([0,1,2],3)