zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    hdu1506(dp)
    windows下安装JMeter
    phpstudy 80端口被占用,修改端口
    久违的phpstorm
    软件项目版本号的命名规则及格式
    phpstudy 局域网访问
    java+eclipse+selenium环境搭建
    软件测试方法汇总
    功能测试大全
    如何有效地描述软件缺陷(Defect)?
  • 原文地址:https://www.cnblogs.com/wenqinchao/p/10587698.html
Copyright © 2011-2022 走看看