演算法題:三數之和

GetaChan發表於2019-11-29

題目來源於力扣

理論基礎

雜湊表

三數之和

題目描述

三數之和

示例

給定 [-1,0,1,2,-1,-4], target=0

解題思路

  1. 暴力解法 O(N^3)

  2. a+b+c=0 O(N^2)

  3. 雙指標

Python 解法

# a+b+c=0
def threeSum(self, nums):
    if len(nums) < 3:
        return []
    nums.sort()
    res = set()
    for i, v in enumerate(nums[:-2]):
        if i >= 1 and v == nums[i-1]:
            continue
        d = {}
        for x in nums[i+1:]:
            if x not in d:
                d[-v-x] = 1
            else:
                res.add((v, -v-x, x))

    return map(list, res)

# 雙指標
def threeSum(self, nums):
    res = []
    nums.sort()
    for i in xrange(len(nums)-2):
        if i > 0 and nums[i] == nums[i-1]:
            cintinue
        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

相關文章