Skip to content

15. 3 Sum

题目

Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.

Notice that the solution set must not contain duplicate triplets.

 

Example 1:

Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Explanation: 
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.
The distinct triplets are [-1,0,1] and [-1,-1,2].
Notice that the order of the output and the order of the triplets does not matter.

Example 2:

Input: nums = [0,1,1]
Output: []
Explanation: The only possible triplet does not sum up to 0.

Example 3:

Input: nums = [0,0,0]
Output: [[0,0,0]]
Explanation: The only possible triplet sums up to 0.

 

Constraints:

  • 3 <= nums.length <= 3000
  • -105 <= nums[i] <= 105
Related Topics
  • 数组
  • 双指针
  • 排序

  • 👍 7492
  • 👎 0
  • 思路一

    本题比较 tricky 如何去除重复的元素。

    • 采用 x in array 判断重复直接超时
    • 采用 set 值为 tuple 后可以通过测试,但是效率还是依然低下
    python
    class Solution:
        def threeSum(self, nums: List[int]) -> List[List[int]]:
            res = set()
            nums.sort()
    
            size = len(nums)
            for i in range(size - 2):
                left = i + 1
                right = size - 1
    
                target = 0 - nums[i]
    
                while left < right:
                    sum = nums[left] + nums[right]
                    if sum == target:
                        temp = (nums[i], nums[left], nums[right])
                        if temp not in res:
                            res.add(temp)
                        left += 1
                        right -= 1
                    elif sum > target:
                        right -= 1
                    else:
                        left += 1
    
            return [[r[0], r[1], r[2]] for r in res]

    复杂度分析

    • 时间复杂度O(N2)
    • 空间复杂度O(N)

    解法二

    思路

    判读重复的元组的开销,不如从源头直接跳过重复的元素

    py
    from typing import List
    # leetcode submit region begin(Prohibit modification and deletion)
    class Solution:
        def threeSum(self, nums: List[int]) -> List[List[int]]:
            res = []
            nums.sort()
    
            size = len(nums)
            for i in range(size - 2):
    
                # 跳过宠物
                if i > 0 and nums[i] == nums[i - 1]:
                    continue
    
                left = i + 1
                right = size - 1
    
                target = 0 - nums[i]
    
                while left < right:
                    sum = nums[left] + nums[right]
                    if sum == target:
                        res.append([nums[i], nums[left], nums[right]])
                        left += 1
                        right -= 1
                        while left < right and nums[left] == nums[left - 1]:
                            left += 1
                        while left < right and nums[right] == nums[right + 1]:
                            right -= 1
                    elif sum > target:
                        right -= 1
                    else:
                        left += 1
    
            return res
    
            
    # leetcode submit region end(Prohibit modification and deletion)
    
    Solution().threeSum([-4,-2,-2,-2,0,1,2,2,2,3,3,4,4,6,6])

    复杂度分析

    • 时间复杂度O(n2)
    • 空间复杂度O(N), N = 有效的元组数量