15. 3Sum

15. 3Sum

題目:
https://leetcode.com/problems/3sum/

難度:

Medium

第一想法,先把nums排序,用三個loop,無法AC

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        n = len(nums)
        res = []
        nums.sort()
        for i in range(n):
            for j in range(i,n):
                for k in range(j,n):
                    if nums[i] + nums[j] + nums[k] == 0 and j != i and k != j and k != i: 
                        curRes = [nums[i],nums[j],nums[k]]
                        if curRes not in res:
                            res.append(curRes)
    
        return res

然后查了一下2sum,用2sum的花樣,因為要排除重復(fù)以及輸出是按照從小到大的輸出:

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        n = len(nums)
        nums.sort()
        self.res = []
        for i in range(n):
            self.twoSum(nums[i+1:], 0-nums[i])
        return [list(i) for i in self.res]
        
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        lookup = {}
        for num in nums:
            if target - num in lookup:
                if (-target ,target - num, num) not in self.res:
                    self.res.append((-target ,target - num, num))
            lookup[num] = target - num
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗。 張土汪:刷leetcod...
    土汪閱讀 12,921評論 0 33
  • LeetCode 第 15 題: 3 Sum。 題目解釋:給定一個整數(shù)陣列 S,找出裡面 3 個 element ...
    就是91閱讀 390評論 0 0
  • 一、題目 二、解題 使用三重循環(huán)遍歷進(jìn)行判斷,得出的結(jié)果使用sort進(jìn)行排序,判斷是否在列表之內(nèi)再添加。 三、嘗試...
    樂樂可愛睡覺閱讀 3,515評論 2 1
  • Medium刷狗家題庫看到的類似的,這個題里面去duplicates的地方值得好好想一想。 為什么我們只在if (...
    greatseniorsde閱讀 189評論 0 0
  • Description: Given an array S of n integers, are there el...
    CharlieGuo閱讀 252評論 0 1

友情鏈接更多精彩內(nèi)容