zoukankan      html  css  js  c++  java
  • 15. 3Sum

    Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

    Note:

    The solution set must not contain duplicate triplets.

    Example:

    Given array nums = [-1, 0, 1, 2, -1, -4],

    A solution set is:
    [
    [-1, 0, 1],
    [-1, -1, 2]
    ]

    Solution1:(TLE)Brute Force

    class Solution:
        def threeSum(self, nums):
            """
            :type nums: List[int]
            :rtype: List[List[int]]
            """
            res = []
            for i in range(len(nums)):
                for j in range(i+1,len(nums)):
                    for k in range(j+1,len(nums)):
                        if nums[i] + nums[j] + nums[k]==0:
                            res.append(tuple(sorted([nums[i],nums[j],nums[k]])))
            return [list(i) for i in set(res)]
    

    267 / 313 test cases passed.

    Solution2:(TLE) Better brute force

    class Solution:
        def threeSum(self, nums):
            """
            :type nums: List[int]
            :rtype: List[List[int]]
            """
            temp = set()
            nums.sort()
            # print(nums)
            for i in range(len(nums)-2):
                if nums[i]>0:  #多加了个剪枝
                    break
                for j in range(i+1,len(nums)-1):
                    if nums[i]+nums[j]>0:
                        break
                    for k in range(j+1,len(nums)):
                        # print('i:',i,'j:',j,'k:',k)
                        # print(nums[i],' ',nums[j],' ',nums[k],' ',nums[i] + nums[j]+nums[k])
                        if nums[i]+nums[j]+nums[k]>0:
                            break
                        if nums[i] + nums[j]+nums[k]==0:
                            temp.add((nums[i],nums[j],nums[k]))
            return [list(i) for i in temp]
    

    283 / 313 test cases passed.

    Solution3:(TLE)

    class Solution:
        def threeSum(self, nums):
            """
            :type nums: List[int]
            :rtype: List[List[int]]
            """
            temp = set()
            nums.sort()
            # print(nums)
            for i in range(len(nums)-2):
                if nums[i]>0: 
                    break
                for j in range(i+1,len(nums)-1):
                    if nums[i]+nums[j]>0:
                        break
                    for k in range(len(nums)-1,j,-1): #倒着搜索更快
                        # print('i:',i,'j:',j,'k:',k)
                        # print(nums[i],' ',nums[j],' ',nums[k],' ',nums[i] + nums[j]+nums[k])
                        if nums[i]+nums[j]+nums[k]<0:
                            break
                        if nums[i] + nums[j]+nums[k]==0:
                            temp.add((nums[i],nums[j],nums[k]))
            return [list(i) for i in temp]
    

    311 / 313 test cases passed.

    Solution4:(TLE)

    class Solution:
        def threeSum(self, nums):
            """
            :type nums: List[int]
            :rtype: List[List[int]]
            """
            temp = set()
            nums.sort()
            for i in range(len(nums)-2):
                if nums[i]>0:
                    break
                left,right = i+1,len(nums)-1
                while left<right:
                    if nums[i]+nums[left]+nums[right]>0:
                        right -= 1
                        continue
                    if nums[i]+nums[left]+nums[right]<0:
                        left += 1
                        continue
                    temp.add((nums[i],nums[left],nums[right]))
                    left += 1
                    right -= 1
            return [list(i) for i in temp]
    

    312 / 313 test cases passed.
    确定了第一项之后,对于后两项用有序序列求和的方式更快。

    Solution5:

    class Solution:
        def threeSum(self, nums):
            """
            :type nums: List[int]
            :rtype: List[List[int]]
            """
            temp = set()
            nums.sort()
            if len(nums)>=3 and nums[0]==nums[-1]==0:  对于全0的数组单独判断
                return [[0,0,0]]
            for i in range(len(nums)-2):
                if nums[i]>0:
                    break
                left,right = i+1,len(nums)-1
                while left<right:
                    if nums[i]+nums[left]+nums[right]>0:
                        right -= 1
                        continue
                    if nums[i]+nums[left]+nums[right]<0:
                        left += 1
                        continue
                    temp.add((nums[i],nums[left],nums[right]))
                    left += 1
                    right -= 1
            return [list(i) for i in temp]
    
  • 相关阅读:
    python 函数
    谷歌浏览器安装POSTMAN
    Django提示Unknown database处理方法
    Django 连接Mysql异常处理
    Django输入 中文参数保存异常解决方法
    vscode过滤pyc文件
    Jenkins启动和停止服务
    执行robot framework 的测试用例 命令行pybot使用方式
    Jenkins定时任务
    Jenkins构建Python项目失败
  • 原文地址:https://www.cnblogs.com/bernieloveslife/p/9783263.html
Copyright © 2011-2022 走看看