Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
无限超时。。。
最后用这个O(n2)复杂度
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if len(nums)<3:
return []
nums = sorted(nums)
ans = []
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 :
if nums[j] + nums[k] == -nums[i]:
ans.append([nums[i],nums[j],nums[k]])
j += 1
k -= 1
while j<k and nums[j] == nums[j-1]:
j += 1
while j<k and nums[k] == nums[k+1]:
k -= 1
elif nums[j] + nums[k] > -nums[i]:
k -= 1
else:
j += 1
return ans