LeetCode 15 [3Sum]

原题

给出一个有n个整数的数组S,在S中找到三个整数a, b, c,找到所有使得a + b + c = 0的三元组。

S = {-1 0 1 2 -1 -4}, 你需要返回的三元组集合的是:
(-1, 0, 1)
(-1, -1, 2)

在三元组(a, b, c),要求a <= b <= c。
结果不能包含重复的三元组。

解题思路

  • 首先,数组排序!!!
  • 遍历数组, 每次check当前数值current往后能不能找到两个数的和等于-current
  • 两个指针中对撞型指针的问题
  • 排序O(nlgn)+遍历O(n2),最终时间复杂度O(n2)
  • 注意有几个地方的代码是为了去掉重复结果
if i != 0 and sortNum[i] == sortNum[i - 1]:
    continue
# 每次left++ 或者 right--之后要记得检查left

完整代码

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res = []
        if not nums:
            return res
            
        sortNum = sorted(nums)
        for i in range(len(sortNum)):
            if i != 0 and sortNum[i] == sortNum[i - 1]:
                continue
            target = - sortNum[i]
            left, right = i + 1, len(sortNum) - 1
            while left < right:
                if sortNum[left] + sortNum[right] == target:
                    res.append([sortNum[i], sortNum[left], sortNum[right]])
                    left += 1
                    right -= 1
                    while left < right and sortNum[left] == sortNum[left - 1]:
                        left += 1
                    while left < right and sortNum[right] == sortNum[right + 1]:
                        right -= 1
                elif sortNum[left] + sortNum[right] > target:
                    right -= 1
                else:
                    left += 1
                    
        return res

你可能感兴趣的:(LeetCode 15 [3Sum])