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的花样,因为要排除重复以及输出是按照从小到大的输出:

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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,975评论 0 33
  • LeetCode 第 15 題: 3 Sum。 題目解釋:給定一個整數陣列 S,找出裡面 3 個 element ...
    就是91阅读 410评论 0 0
  • 一、题目 二、解题 使用三重循环遍历进行判断,得出的结果使用sort进行排序,判断是否在列表之内再添加。 三、尝试...
    乐乐可爱睡觉阅读 3,519评论 2 1
  • Medium刷狗家题库看到的类似的,这个题里面去duplicates的地方值得好好想一想。 为什么我们只在if (...
    greatseniorsde阅读 216评论 0 0
  • Description: Given an array S of n integers, are there el...
    CharlieGuo阅读 263评论 0 1

友情链接更多精彩内容