-
Notifications
You must be signed in to change notification settings - Fork 0
/
16. 3Sum Closest
48 lines (45 loc) · 1.59 KB
/
16. 3Sum Closest
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
# 12:21 -->
class Solution(object):
def threeSumClosest(self, num, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
num.sort()
result = num[0] + num[1] + num[2]
for i in range(len(num) - 2):
j, k = i+1, len(num) - 1
while j < k:
sum = num[i] + num[j] + num[k]
if sum == target:
return sum
if abs(sum - target) < abs(result - target):
result = sum
if sum < target:
j += 1
elif sum > target:
k -= 1
return result
# nums.sort()
# diff = 1000000
# for i in xrange(len(nums) - 2):
# start, end = i + 1, len(nums) - 1
# sums = nums[start] + nums[end] + nums[i]
# while start + 1 < end:
# sums = nums[start] + nums[end] + nums[i]
# if sums == target:
# return target
# elif sums > target:
# end -= 1
# else:
# start += 1
# newnums = nums[start] + nums[end] + nums[i]
# if abs (target - sums) < diff:
# diff = abs (target - sums)
# result = sums
# if abs (target - newnums) < diff:
# diff = abs (target - newnums)
# result = newnums
# # print diff, result, nums[i], nums[start], nums[end]
# return result