LeetCode_Everyday:015 3Sum

LeetCode_Everyday:015 3Sum


LeetCode Everyday:堅持價值投資,做時間的朋友!!!

題目:

給你一個包含 n 個整數的數組nums,判斷nums中是否存在三個元素a,b,c,使得a + b + c = 0?請你找出所有滿足條件且不重複的三元組。
注意:答案中不可以包含重複的三元組。

示例:

  • 示例 1:
    給定數組 nums = [-1, 0, 1, 2, -1, -4],
    
    滿足要求的三元組集合爲:
    [
      [-1, 0, 1],
      [-1, -1, 2]
    ]
    

代碼

方法一: 集合的思路

執行用時:676 ms, 在所有 Python3 提交中擊敗了93.05%的用戶
內存消耗:17 MB, 在所有 Python3 提交中擊敗了6.02%的用戶

class Solution:
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res = []
        nums.sort()
        for i in range(len(nums)):
            if nums[i] > 0:
                break
            if i >= 1 and nums[i] == nums[i-1]:
                continue
            target = -nums[i]
            cache = set()
            for j in range(i+1, len(nums)):
                if nums[j] in cache:
                    if len(res) == 0 or res[-1]!=[nums[i], target-nums[j], nums[j]]:
                        res.append([nums[i], target-nums[j], nums[j]])
                cache.add(target-nums[j])
        return res

"""
For Example:    input:   nums = [-1, 0, 1, 2, -1, -4]
               output:   [
                          [-1, 0, 1],
                          [-1, -1, 2]
                         ]
"""
nums = [-1, 0, 1, 2, -1, -4]
                
solution = Solution()
result = solution.threeSum(nums)
print('輸出爲:', result)

方法二: 排序+雙指針

執行用時 :44 ms, 在所有 Python3 提交中擊敗了59.87%的用戶
內存消耗 :13.7 MB, 在所有 Python3 提交中擊敗了6.15%的用戶

class Solution:
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        n=len(nums)
        res=[]
        if(not nums or n<3):
            return []
        nums.sort()
        res=[]
        for i in range(n):
            if(nums[i]>0):
                return res
            if(i>0 and nums[i]==nums[i-1]):
                continue
            L=i+1
            R=n-1
            while(L<R):
                if(nums[i]+nums[L]+nums[R]==0):
                    res.append([nums[i],nums[L],nums[R]])
                    while(L<R and nums[L]==nums[L+1]):
                        L=L+1
                    while(L<R and nums[R]==nums[R-1]):
                        R=R-1
                    L=L+1
                    R=R-1
                elif(nums[i]+nums[L]+nums[R]>0):
                    R=R-1
                else:
                    L=L+1
        return res

"""
For Example:    input:   nums = [-1, 0, 1, 2, -1, -4]
               output:   [
                          [-1, 0, 1],
                          [-1, -1, 2]
                         ]
"""
nums = [-1, 0, 1, 2, -1, -4]
                
solution = Solution()
result = solution.threeSum(nums)
print('輸出爲:', result)

參考

  1. https://www.bilibili.com/video/BV1ek4y1d7sw
  2. https://leetcode-cn.com/problems/3sum/solution/pai-xu-shuang-zhi-zhen-zhu-xing-jie-shi-python3-by/

此外

  • 原創內容轉載請註明出處
  • 請到我的GitHub點點 star
  • 關注我的 CSDN博客
  • 關注我的嗶哩嗶哩
  • 關注公衆號:CV伴讀社

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章