NYUer | LeetCode15 3Sum

LeetCode15 3Sum


Author: Stefan Su
Create time: 2022-10-31 19:46:29
Location: New York City, NY, USA

Description 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.
Constrains
  • 3 <= nums.length <= 3000
  • -105 <= nums[i] <= 105

Analysis

Two pointers version in this problem is better than hash version. For details, see comments in code.

Solution

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """

        # two pointer version

        result = []

        nums = sorted(nums)
        # go through first number of three numbers
        for i in range(len(nums)):
            # if this number larger than 0, break the for loop, since nums[left] and nums[right] must larger than 0
            if nums[i] > 0:
                break
            # KEY OPERATION: remove duplication operation for i
            # For example: nums = [-1, -1, -1, 2]
            # we get nums[0] + nums[2] + nums[3] = 0, but also nums[1] + nums[2] + nums[3] = 0
            # but the same value in result [-1, -1, 2]
            # therefore, we should compare current i with previous one
            if nums[i] == nums[i-1] and i > 0:
                continue

            # initialize left and right
            left = i + 1
            right = len(nums) - 1
            while right > left:
                # print('i = ', i)
                # print(nums[i], nums[left], nums[right])
                # if nums[i] + nums[left] + nums[right] > 0, then move right index to a previous index
                if nums[i] + nums[left] + nums[right] > 0:
                    right -= 1
                # if nums[i] + nums[left] + nums[right] < 0, then move left index to a latter index
                elif nums[i] + nums[left] + nums[right] < 0:
                    left += 1
                else:
                    # append current valid list into result
                    result.append([nums[i], nums[left], nums[right]])
                    # KEY OPERATION: remove duplication operation for right
                    # if nums[right] == nums[right - 1], then move right to a previous index
                    # For example, nums = [-1, -1, -1, 0, 0, 0, 1, 1, 1]
                    # current is nums[0] + nums[3] + nums[8] = 0
                    # but if we replace nums[8] with nums[7] or nums[6], it works as well
                    # therefore, we should move right index to remove this duplicated output
                    # although, the index of value 1 can be different (6, 7, 8)
                    while right > left and nums[right] == nums[right - 1]:
                        right -= 1
                    # KEY OPERATION: remove duplication operation for left
                    # if nums[left] == nums[left + 1], then move left to a latter index
                    # same explanation as movement of right index
                    while right > left and nums[left] == nums[left + 1]:
                        left += 1
                    left += 1
                    right -= 1

            # print('result = ', result)

        return result

Hopefully, this blog can inspire you when solving LeetCode15. For any questions, please comment below.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值