码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 15.三数之和

时间:2020-07-04 01:30:22      阅读:51      评论:0      收藏:0      [点我收藏+]

标签:add   判断   深度   深度优先   重复   元素   存在   res   etc   

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

示例:
给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]

难点:不能重复

1、深度优先搜索(回溯)(提交后判定超时)

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        ans = set()
        cur = []
        nums = sorted(nums)
        print(nums)
        self.threeSum_solver(nums,ans,cur,0)
        result = []
        for a in ans:
            result.append([int(i) for i in a.split(‘,‘)])
        return result
    
    def threeSum_solver(self,nums,ans,cur,s):
        if len(cur) > 3:
            return
        if len(cur)==3 and sum(cur)==0:
            ans.add(‘,‘.join([str(x) for x in cur]))
            return
        for i in range(s,len(nums)):
            #if i>0 and nums[i-1]==nums[i]:
            #    continue
            cur.append(nums[i])
            self.threeSum_solver(nums,ans,cur,i+1)
            cur.pop()

2、双指针

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        nums = sorted(nums)
        nums_len = len(nums)
        answer = []
        for i in range(0, nums_len - 2):
            if nums[i] > 0:
                break
            """去重:nums[i-1]已经搜索过了,重复nums[i]直接跳过"""
            if i > 0 and nums[i] == nums[i-1]:
                continue
            j = i + 1
            k = nums_len - 1
            while j < k:
                total = nums[i] + nums[j] + nums[k]
                if total == 0:
                    answer.append([nums[i], nums[j], nums[k]])
                    j += 1
                    k -= 1
                    """去重:已经搜索过的值,直接跳过(注意要先加1,再判断是否需要跳过)"""
                    while j < k and nums[j] == nums[j-1]:
                        j += 1
                    while j < k and nums[k] == nums[k+1]:
                        k -= 1
                elif total > 0:
                    k -= 1
                    while j < k and nums[k] == nums[k+1]:
                        k -= 1
                else:
                    j += 1
                    while j < k and nums[j] == nums[j-1]:
                        j += 1
        return answer

LeetCode 15.三数之和

标签:add   判断   深度   深度优先   重复   元素   存在   res   etc   

原文地址:https://www.cnblogs.com/sandy-t/p/13233186.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!