zoukankan      html  css  js  c++  java
  • 力扣-15-三数之和

    问题:

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

    方法一:BF(submit超时)

    # leetcode submit region begin(Prohibit modification and deletion)
    class Solution(object):
        def threeSum(self, nums):
            """
            :type nums: List[int]
            :rtype: List[List[int]]
            """
            nums.sort()
            res = []
            length = len(nums)
            for i in range(length-2):
                if nums[i] != nums[i-1] or i == 0:
                    for j in range(i+1, length-1):
                        if nums[j] != nums[j-1] or j==i+1:
                            for k in range(j+1, length):
                                if nums[k] != nums[k-1] or k==j+1:
                                    if nums[i] + nums[j] + nums[k] == 0:
                                        res.append([nums[i], nums[j], nums[k]])
            return res
    # leetcode submit region end(Prohibit modification and deletion)

    方法二:排序+双指针(左右夹逼)

    # leetcode submit region begin(Prohibit modification and deletion)
    class Solution(object):
        def threeSum(self, nums):
            """
            :type nums: List[int]
            :rtype: List[List[int]]
            """
            nums.sort()
            res = []
            length = len(nums)
            for i in range(length):
                if i > 0 and nums[i] == nums[i-1]: continue
                left, right = i + 1, length-1
                while left < right:
                    v = nums[i] + nums[left] + nums[right]
                    if v < 0:
                        left += 1
                    elif v > 0:
                        right -= 1
                    else:
                        res.append([nums[i], nums[left], nums[right]])
                        while left < right and nums[left] == nums[left+1]: left+=1
                        while left < right and nums[right] == nums[right-1]: right-=1
                        left += 1
                        right -= 1
            return res
    # leetcode submit region end(Prohibit modification and deletion)
    时刻记着自己要成为什么样的人!
  • 相关阅读:
    VSCode一键调用DOSBox运行MASM/TASM代码的自定义任务
    C# | VS2019连接MySQL的三种方法以及使用MySQL数据库教程
    Visual Studio 2019连接MySQL数据库详细教程
    Visual Studio 2022 激活码
    Python | 使用SVM支持向量机进行鸢尾花分类
    Python | __init__.py的神奇用法
    Java简单介绍及Java生态
    NoSQL:一个帝国的崛起
    学习哪门语言好
    浅析HTTP协议
  • 原文地址:https://www.cnblogs.com/demo-deng/p/14773590.html
Copyright © 2011-2022 走看看