您的位置:首页 > 其它

[Leetcode] 15. 3Sum

2017-04-15 23:23 260 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: