3sum(leetcode)

来源:互联网 发布:淘宝网全屏轮播代码 编辑:程序博客网 时间:2024/06/12 14:05

题目:

       

        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.

        Note:

  •        Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  •         The solution set must not contain duplicate triplets.
  • For example, given array S = {-1 0 1 2 -1 -4},    A solution set is:    (-1, 0, 1)    (-1, -1, 2)
解题思路1:
使用最为朴素的方法,即为3个for循环进行遍历。但时间复杂度为O(n**3)。无法通过测试
代码:
class Solution:
    # @return a list of lists of length 3, [[val1,val2,val3]]
    def threeSum(self, num):    
        def swap(i,j,k):
            l=[i,j,k]
            r return sorted(l)
        list = []
        n = len(num)
        for i in range(n-2):
            for j in range(i+1,n-1):
                for k in range(j+1,n):
                    list_tmp = swap(num[i],num[j],num[k])
                    if num[i]+num[j]+num[k]==0 and list_tmp not in list:
                        list.append(list_tmp)
        return list
解题思路2:
首先对数组进行排序,然后再进行类似二分的夹逼搜索。时间复杂度为O(n**2)
代码:
class Solution:
    # @return a list of lists of length 3, [[val1,val2,val3]]
    def threeSum(self, num):
        n = len(num)
        ans =[]
        num = sorted(num)
        for i in range(n-2):
            low = i+1
            high = n-1
            while low<high:
                if num[low]+num[high]+num[i]==0 and [num[i],num[low],num[high]] not in ans:
                    ans.append([num[i],num[low],num[high]])
                    low += 1
                elif num[low]+num[high]+num[i]<0:
                    low += 1
                    continue
                elif num[low]+num[high]+num[i]>0:
                    high -= 1
                    continue
                else:
                    low += 1
        return ans
0 0
原创粉丝点击