[Leetcode] 15. 3Sum

来源:互联网 发布:海岛奇兵建筑升级数据 编辑:程序博客网 时间:2024/06/06 19:33

Given an array S of n integers, are there elements abc 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

0 0
原创粉丝点击