3 Sum

Intuition

The problem asks to find all unique triplets in the given array such that the sum of the three elements is equal to zero. The solution set must not contain duplicate triplets.

Approach

The provided solution uses a two-pointer approach along with sorting the array. The idea is to fix one element (nums[i]) and use two pointers (left and right) to find the other two elements such that their sum equals zero.

Sort the array nums to make it easier to find unique triplets.
Iterate through the sorted array, fixing one element nums[i].
Use two pointers (left and right) to find the other two elements. Adjust the pointers based on the sum of the three elements:
If the sum is greater than zero, move the right pointer to the left.
If the sum is less than zero, move the left pointer to the right.
If the sum is zero, add the triplet to the result and move the pointers while skipping duplicate elements.
Return the result.

Complexity

  • Time complexity:

The time complexity of this solution is O(n^2), where n is the length of the input array nums. The dominant factors are the sorting step (O(n log n)) and the two-pointer iteration (O(n)).

  • Space complexity:

The space complexity is O(1), as the solution uses only a constant amount of space to store the result.

Code

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        stack=[]
        nums = sorted(nums)
        for i,a in enumerate(nums):
            if i>0 and a==nums[i-1]:
                continue
            left,right=i+1,len(nums)-1
            while left < right:
                threesum = nums[i] + nums[left] + nums[right]
                if threesum > 0:
                    right-=1
                elif threesum < 0:
                    left+=1
                else:
                    stack.append([nums[i],nums[left],nums[right]])
                    left+=1
                    while nums[left] == nums [left-1] and left < right:
                         left+=1
                         
        return stack
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值