Leetcode P15 three sum @python Lang (LL)

9 篇文章 0 订阅
9 篇文章 0 订阅

Leetcode P15 three sum @python Lang (LL)

Link: https://leetcode.com/problems/3sum/

Content:
在这里插入图片描述
Method 1 - Brute Force
Algorithm:

  1. nums sort
  2. return is a list, build an empty array - res = []
  3. traverse i from 0 to len(nums-2)
    traverse j from i+1 to len(nums-1)
    traverse k from j+1 to len(nums)
  4. if nums[i] + num[j] + nums[k] == 0 and this result has not in res[], return

Code:

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        nums.sort()
        length=len(nums)
        res=[]
        for i in range(length):
            for j in range (i+1,length):
                for k in range(j+1,length):
                    sum=nums[i]+nums[k]+nums[j]
                    if sum==0 and not [nums[i],nums[j],nums[k]] in res:
                    # to avoid duplicate triplets
                        res.append([nums[i],nums[j],nums[k]])
        return res

Attention ** Time Limit Exceeded**

Method 2 - Two pointers
Algorithm:

  1. nums sort
  2. return is a list, build an empty array - res = []
  3. traverse i, for loop, turn this problem to 2 sum.
    two pointers, left from i+1, right from len(nums-1)
  4. limit condition: while left < right
    s = nums[i] + nums[left] + nums[right]
    if s>0, right–; if s<0, left++
    if s==0, res.append, left++, right–, return res

Code:

def threeSum(nums):
    """
    :type nums: List[int]
    :rtype: List[List[int]]
    """
    res = []
    nums.sort()
    for i in range(len(nums)-2):
        if i == 0 or nums[i] > nums[i-1]: # first avoid duplicate
            left = i+1
            right = len(nums)-1
            while left < right:
                s = nums[i] + nums[left] + nums[right]
                if s == 0:
                    res.append([nums[i], nums[left], nums[right]])
                    left += 1
                    right -= 1
                    if nums[left] == nums[left-1]: # these two if, second to avoid duplicate
                        left += 1
                    if nums[right] == nums[right+1]:
                        right -= 1
                elif s > 0:
                    right -= 1
                else:
                    left += 1
    return res

Time complexity:
O(n2)

Something needs to be noticed:
There are two places to avoid the duplicate triplets for method 2

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值