leetcode刷题记录 1.3 nSum问题

两数之和

https://leetcode.cn/problems/two-sum/
解法:哈希表,时间和空间复杂度都是O(n)

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        hashtable = {}
        for i, item in enumerate(nums):
            if (target - item) in hashtable:
                return [hashtable[target-item], i]
            hashtable[item] = i
        return []        

变体:如果不是返回idx,而是返回元素值,可以排序+双指针,O(nlogn)

https://leetcode.cn/problems/3sum/description/

思路:排序 + 双指针

class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        n = len(nums)
        if (n < 3):
            return []
        res = []
        nums.sort()
        for i in range(n):
            if (nums[i] > 0):
                return res
            # 对nums[i]去重
            if (i > 0 and nums[i] == nums[i-1]): 
                i += 1
                continue
            L = i+1
            R = n-1
            while (L < R):
                if (nums[i] + nums[L] + nums[R] == 0):
                    res.append([nums[i], nums[L], nums[R]])
                    # 对nums[L]去重
                    while(L < R and nums[L] == nums[L+1]):
                        L += 1
                    # 对nums[L]去重
                    while(L < R and nums[R] == nums[R-1]):
                        R -= 1  
                    # 移动指针,这步容易忘
                    L += 1
                    R -= 1
                elif (nums[i] + nums[L] + nums[R] > 0):
                    R -= 1
                else:
                    L += 1
        return res
                

时间复杂度:O(n2)
空间复杂度: O(1) (取决于排序算法)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值