leetcode 01 两数和

本文探讨了LeetCode经典题目“两数之和”的三种解法,包括遍历查找、双端队列优化及哈希表快速匹配。通过对不同算法的时间和空间复杂度分析,展示了如何在效率与资源间取得平衡。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

leetcode 01 两数和

解法一:

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for index, num in enumerate(nums, 0):
            if (target - num) in nums[index + 1: ]:
                i = nums[index + 1:].index(target - num) + 1 + index
                return [index, i]
        return []
# 耗时988ms
# 内存13.6mb

解法二:

# 使用双端队列实现  想通过双端队列减少列表切片操作 所占用的额外内存大小 结果差距不大
from collections import deque
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        d = deque(nums)
        i = 0
        lhs = d.popleft()
        while d:
            if (target - lhs) in d:
                index = d.index(target - lhs) + i + 1
                return [i, index]
            i += 1
            lhs = d.popleft()
        return []
# 耗时 968ms
# 内存 13.5mb

解法三:

# 使用hashmap 减少查找时间
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        hashmap = {}
        for index, num in enumerate(nums):
            lhs = target - num
            if lhs in hashmap:
                return [hashmap[lhs], index]
            hashmap[num] = index
        return []
     
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值