算法-3Sum问题

给定一个列表,在列表中找出3个数字,使得a+b+c=0.找到所有不同的组合
For example, given array S = [-1, 0, 1, 2, -1, -4],

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

第一次尝试:暴力解法O(n^3)

用三层循环,直到找出所有解。但这样做有2个问题。第一个是超时,O(n^3)的解法肯定炸了;第二个问题是不满足题意。因为会得到如下结果, 会有重复的:
[
  [-1, 0, 1],
  [0, 1, -1],
  [-1, 2, -1]
]

第二次尝试:O(n^2logn)

要解决上述的问题,就需要更快的算法,其次解决重复也很容易。所以很自然想到排序+二分查找。先找到遍历a+b,然后在剩余列表下查找-a-b。用到的库是bisect库。排序的复杂度为O(nlogn)-O(n^2), 不会拖累整个算法。
import bisect
class Solution(object):
    def threeSum(self, nums):
        if len(nums) < 3:
            return []
        nums.sort()
        l = len(nums)
        result = []
        for i in range(l-1):
            for j in range(i+1,l-1):
                wanna_find = 0 - nums[i] - nums[j]
                location = bisect.bisect_left(nums, wanna_find, j+1, l-1)
                if nums[i] + nums[j] + nums[location] == 0:
                    if [nums[i],nums[j],nums[location]] not in result:
                        result.append([nums[i],nums[j],nums[location]])
        return result
本以为能通过的,但是最后结果是311/313, 还是超时了。显然需要更快的算法,即O(n^2)

第二次尝试:O(n^2)

既然如此选择,那么要做的就是:在一个有序列表中,以线性时间内找到a+b=-c。这样子的算法之前也见过,有2个索引s,e分别从列表头,和列表尾开始遍历。如果nums[s]+nums[e]<-c, 则s += 1;若nums[s]+sums[e]>-c, 则e -= 1。
class Solution(object):
    def threeSum(self, nums):
        nums.sort()
        l = len(nums)
        result = []
        for i in range(l-1):
            s, e = i+1, l-1
            while s < e:
                r = nums[i] + nums[s] + nums[e]
                if r < 0:
                    s += 1
                elif r > 0:
                    e -= 1
                if s >= e:
                    break
                if r == 0:
                    s += 1
                    e -= 1
                    if [nums[i],nums[s-1],nums[e+1]] not in result:
                        result.append([nums[i],nums[s-1],nums[e+1]])
        return result

另一个类似解法, 不知道为啥居然更快

class Solution(object):
    def threeSum(self, nums):
        res = []
        nums.sort()
        for i in xrange(len(nums)-2):
            if i > 0 and nums[i] == nums[i-1]:
                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]))
                    while l < r and nums[l] == nums[l+1]:
                        l += 1
                    while l < r and nums[r] == nums[r-1]:
                        r -= 1
                    l += 1; r -= 1
        return res

另一个相关问题3Sum Closest

Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
class Solution:
    # @return an integer
    def threeSumClosest(self, num, target):
        num.sort()
        result = num[0] + num[1] + num[2]
        for i in range(len(num) - 2):
            j, k = i+1, len(num) - 1
            while j < k:
                sum = num[i] + num[j] + num[k]
                if sum == target:
                    return sum

                if abs(sum - target) < abs(result - target):
                    result = sum

                if sum < target:
                    j += 1
                elif sum > target:
                    k -= 1

        return result
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值