15. 3Sum



15. 3Sum (Medium) 三数之和

题干

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:

解题思路

我的歪思路

时间复杂度太高

另外犯了一个错误,三个不确定元素时,要先确定一个元素,把模型复杂度降低,然后再考虑其他不确定元素

可行思路

注意去重:

  1. 第一个循环元素,不能重复
  2. left元素,不能重复

优化思路

因为是三个元素,无法继续优化时间复杂度,只能优化一下边界,减少计算时间

优化边界产生的效果,强依赖样本。最差的情况下可能毫无优化。

答案

我的错误答案(耗时不可接受)

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        answer = []

        left_i = 0
        right_i = len(nums) - 1
        while left_i <= right_i - 2:
            middle_v = -(nums[left_i] + nums[right_i])

            # 左绝对值大
            if middle_v > 0:
                for middle_i in range(right_i-1, left_i, -1):
                    if nums[middle_i] == middle_v:
                        pair = [nums[left_i], middle_v, nums[right_i]]
                        if pair not in answer:
                            answer.append(pair)
                        right_i -= 1
                        break
                    # 左绝对值大,找不到
                    if nums[middle_i] < middle_v:
                        left_i += 1
                        break
                continue

            # 右绝对值大
            for middle_i in range(left_i+1, right_i):
                if nums[middle_i] == middle_v:
                    pair = [nums[left_i], middle_v, nums[right_i]]
                    if pair not in answer:
                        answer.append(pair)
                    left_i += 1
                    break
                # 右绝对值大,找不到
                if nums[middle_i] > middle_v:
                    right_i -= 1
                    break
        
        return answer

可行答案

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        answer = []

        for i in range(len(nums)-2):
            if i > 0 and nums[i-1] == nums[i]:
                continue
            
            left = i + 1
            right = len(nums) - 1
            while left < right:
                sum_res = sum([nums[i], nums[left], nums[right]])
                if sum_res > 0:
                    right -= 1
                elif sum_res < 0:
                    left += 1
                else:
                    answer.append([nums[i], nums[left], nums[right]])
                    while left < right and nums[left] == nums[left+1]:
                        left += 1
                    while left < right and nums[right] == nums[right-1]:
                        right -= 1
                    left += 1
                    right -= 1
        
        return answer

优化答案

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        answer = []

        for i in range(len(nums)-2):
            # 优化边界
            if nums[i] > 0:
                break
            
            # 跳过重复
            if i > 0 and nums[i-1] == nums[i]:
                continue
            
            left, right = i + 1, len(nums) - 1

            # 优化边界
            target = -nums[i]
            max_match = nums[right-1] + nums[right]
            min_match = nums[left] + nums[left-1]
            if target > max_match or target < min_match:
                continue

            while left < right:
                sum_res = sum([nums[i], nums[left], nums[right]])
                if sum_res > 0:
                    right -= 1
                elif sum_res < 0:
                    left += 1
                else:
                    answer.append([nums[i], nums[left], nums[right]])
                    # 优化边界
                    while left < right and nums[left] == nums[left+1]:
                        left += 1
                    while left < right and nums[right] == nums[right-1]:
                        right -= 1
                    left += 1
                    right -= 1
        
        return answer