classSolution(object):defthreeSum(self, nums):
nums.sort()
l = len(nums)
result = []
for i in range(l-1):
s, e = i+1, l-1while s < e:
r = nums[i] + nums[s] + nums[e]
if r < 0:
s += 1elif r > 0:
e -= 1if s >= e:
breakif r == 0:
s += 1
e -= 1if [nums[i],nums[s-1],nums[e+1]] notin result:
result.append([nums[i],nums[s-1],nums[e+1]])
return result
另一个类似解法, 不知道为啥居然更快
classSolution(object):defthreeSum(self, nums):
res = []
nums.sort()
for i in xrange(len(nums)-2):
if i > 0and nums[i] == nums[i-1]:
continue
l, r = i+1, len(nums)-1while l < r:
s = nums[i] + nums[l] + nums[r]
if s < 0:
l +=1elif s > 0:
r -= 1else:
res.append((nums[i], nums[l], nums[r]))
while l < r and nums[l] == nums[l+1]:
l += 1while l < r and nums[r] == nums[r-1]:
r -= 1
l += 1; r -= 1return res
另一个相关问题3Sum Closest
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
class Solution:
# @return an integer
def threeSumClosest(self, num, target):
num.sort()
result = num[0] + num[1] + num[2]
for i in range(len(num) - 2):
j, k = i+1, len(num) - 1while j < k:
sum = num[i] + num[j] + num[k]
ifsum == target:
returnsumifabs(sum - target) < abs(result - target):
result = sumifsum < target:
j += 1
elif sum > target:
k -= 1returnresult