• 3 sum


    问题:寻找数组中3个和为0的所有数字组合,要求不能重复

    示例:

    输入:[-2,3,-1,1,-1,2]

    输出:[[-2,-1,3],[-1,-1,2]]

    解决思路:固定其中一个数,对另外两个数进行考察

    Python代码:

    class Solution(object):
        def threeSum(self, nums):
            """
            :type nums: List[int]
            :rtype: List[List[int]]
            """
        
            out = []
            nums.sort()
            for i in range(len(nums)-2):
                if i > 0 and nums[i] == nums[i-1]:
                    continue
                else:
                    start = i + 1
                    end = len(nums) - 1
                    while start < end:
                        num2sum = nums[start] + nums[end]
                        if num2sum < -nums[i] or (start>i+1 and nums[start]==nums[start-1]):
                            start += 1
                        elif num2sum > -nums[i] or (end < len(nums)-1 and nums[end] == nums[end+1]):
                            end -= 1
                        else:
                            out.append([nums[i],nums[start],nums[end]])
                            start += 1
                            end -= 1
            return out

    Python代码2

    (转自leetcode用户WangQiuc)

    class Solution(object):
        def threeSum(self, nums):
            """
            :type nums: List[int]
            :rtype: List[List[int]]
            """
            if len(nums) < 3: return []
            counter = collections.Counter(nums)
            out = [[0,0,0]] if counter[0]>2 else []
            neg, pos = [x for x in counter if x < 0], [x for x in counter if x >= 0]
            for n in range(len(neg)):
                if n > 0 and neg[n] == neg[n-1]
                for p in pos:
                    x = -n-p
                    if x in counter:
                        if x in [n,p] and counter[x] > 1: 
                            out.append([n,x,p])
                        elif x < n:
                            out.append([x,n,p])
                        elif x > p:
                            out.append([n,p,x])
            return out
  • 相关阅读:
    codeforces 1215 E Marbles-----状压DP
    留坑待填
    Catalan数
    砝码称重
    约数和
    硬币题解
    迎春舞会之数字舞蹈
    过剩数
    猜测棋局
    [NOIP普及组2014第三题]螺旋矩阵
  • 原文地址:https://www.cnblogs.com/wenqinchao/p/10587698.html
Copyright © 2020-2023  润新知