LeetCode Notes_#15 3Sum

LeetCode Notes_#15 3Sum

Contents

题目

Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

triplets=>triple lets三胞胎,这里是三元组的意思

Note:

The solution set must not contain duplicate triplets.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]

思路和解答

思路

  • 第一想法:好像就只能暴力循环这样去加?
  • 还可以这样,先加两个数得到一个sum,然后找有没有sum的相反数?(而且这个相反数不能是两个数之一)
  • 疑问:每一个三元素list里边的数字有顺序要求吗?

解答

#尝试暴力循环
class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res=[]
        for i in range(len(nums)):
            for j in range(i+1,len(nums)):
                for k in range(j+1,len(nums)):
                    if nums[i]+nums[k]+nums[j]==0:
                        res.append([nums[i],nums[j],nums[k]])
        return res

逻辑没有问题,但是结果的细节有点出入,就是会出现两次元素相同的三元组,那么需要再处理一下,每个三元list内部排一下序,然后先加入set,避免重复,最后转化为list并返回

#尝试第二次
class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        resSet={}
        res=[]
        for i in range(len(nums)):
            for j in range(i+1,len(nums)):
                for k in range(j+1,len(nums)):
                    if nums[i]+nums[k]+nums[j]==0:
                        resElement=[nums[i],nums[j],nums[k]]
                        resElement.sort()
                        if resElement not in res:
                            res.append(resElement)
        # resSet={res}
        # res=list(resSet)
        return res

改了一下,答案肯定没错了,但是暴力循环再次超时,

#最后的解答还是照着discussion敲的,emmm
class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res=[]
        nums.sort()
        for i in range(len(nums)-2):#因为找的是三个数,所以不能遍历到最后,要提前结束
            if i>0 and nums[i]==nums[i-1]:#先固定一个数nums[i],再去找另两个数,固定的这个数只需要一次就可以了,重复的就跳过
                continue
            l,r=i+1,len(nums)-1#左右指针
            while(l<r):
                s=nums[i]+nums[l]+nums[r]
                if s<0:#如果结果小了,那么将他调整大一点
                    l+=1
                elif s>0:#如果结果大了,那么将他调整小一点
                    r-=1
                else:
                    res.append((nums[i],nums[l],nums[r]))#插入到res最后
                    while l<r and nums[l]==nums[l+1]:#两个while语句用来快速移动指针,直到没有出现相邻重复数字
                        l+=1
                    while l<r and nums[r]==nums[r-1]:
                        r-=1
                    l+=1#如果s=0了,也要继续移动指针
                    r-=1
        return res

这大概是目前为止做到的比较复杂的一道题了,之前的套路不太管用...

posted @ 2018-11-08 20:16  Howfar's  阅读(125)  评论(0编辑  收藏  举报