zoukankan      html  css  js  c++  java
  • leetcode15:三数之和

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

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

    ============================Python=========================

    class Solution:
        def threeSum(self, nums: List[int]) -> List[List[int]]:
            res = []
            if not nums or len(nums) < 3:
                return res
            nums.sort()
            for i in range(len(nums)):
                if nums[i] > 0:
                    return res
                if i > 0 and nums[i] == nums[i-1]:
                    continue
                left = i + 1
                right = len(nums) - 1
                while (left < right):
                    if nums[i] + nums[left] + nums[right] == 0:
                        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
                    elif nums[left] + nums[right] + nums[i] > 0:
                        right -= 1
                    else:
                        left += 1
            return res

    ===============================Go===============================

  • 相关阅读:
    日报10.11
    日报10.9
    日报10.8
    日报10.7
    换马甲啦
    CSP2019知识点整理
    字符logo存档
    QHDYZ模拟赛20191027 提前透题
    数竞大佬jhc的三角函数复习题
    IO流
  • 原文地址:https://www.cnblogs.com/liushoudong/p/13493698.html
Copyright © 2011-2022 走看看