zoukankan      html  css  js  c++  java
  • LeetCode 15. 三数之和

    15. 三数之和

    Difficulty: 中等

    给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 _a,b,c ,_使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。

    注意:答案中不可以包含重复的三元组。

    示例 1:

    输入:nums = [-1,0,1,2,-1,-4]
    输出:[[-1,-1,2],[-1,0,1]]
    

    示例 2:

    输入:nums = []
    输出:[]
    

    示例 3:

    输入:nums = [0]
    输出:[]
    

    提示:

    • 0 <= nums.length <= 3000
    • -10<sup>5</sup> <= nums[i] <= 10<sup>5</sup>

    Solution

    解法一:暴力解法,时间复杂度为O(N^3),嵌套了三层循环

    class Solution:
        def threeSum(self, nums: List[int]) -> List[List[int]]:
            nums.sort()
            res = []
            for i in range(len(nums)):
                tmp = self.twoSumHelper(nums[i+1:], 0-nums[i])
                for item in tmp:
                    item.append(nums[i])
                    res.append(item)
            return [list(t) for t in set(tuple(_) for _ in res)]
        
        def twoSumHelper(self, nums, target):
            d, ans = {}, []
            for i in range(len(nums)):
                if target - nums[i] in d:
                    ans.append([nums[i], target - nums[i]])
                d[nums[i]] = i
            return ans
    

    解法二:时间复杂度为O(N^2),思路是求a+b+c=0,等价于a=-(b+c),即在nums[i+1:]列表中寻找满足-(b+c)的数字。

    class Solution:
        def threeSum(self, nums: List[int]) -> List[List[int]]:
            if len(nums) < 3: 
                return []
            nums.sort()
            res = set()
            
            for i, v in enumerate(nums[:-2]):
                if i >= 1 and v == nums[i-1]:
                    continue
                d = {}
                for x in nums[i+1:]:
                    if x not in d:
                        d[-v-x] = 1
                    else:
                        res.add((v, -v-x, x))
            return list(res)
    
  • 相关阅读:
    python 发邮件乱码
    膳魔师杯使用注意事项
    了解指针,分分钟的事情 C++筆記--指針
    海淘攻略
    【转】Cocos2dx.3x入门三部曲
    在Windows7上搭建Cocos2d-x 3.2alpha0开发环境
    黑苹果 MAC OS X 10.10.2 安装流程
    Linux 下如何查找木马并处理
    js如何判断访问是来自搜索引擎(蜘蛛人)还是直接访问
    泰*网 Centos 一些命令
  • 原文地址:https://www.cnblogs.com/swordspoet/p/14348879.html
Copyright © 2011-2022 走看看