【Leetcode笔记】两数之和

Leetcode原题链接:两数之和

一、一般题解

暴力解法,排列组合遍历解决。

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for i in range(len(nums)):
            for j in range(i+1, len(nums)):
                if nums[i] + nums[j] == target:
                    return i,j

时间复杂度O(n²)。

二、哈希表解法

  • 准备一个字典,存放遍历的数:{数值:下标}。
  • 从第一个数开始遍历,寻找 target 减当前数值是否存在于字典中,存在则返回下标,不存在则继续遍历。
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        records = {}

        for idx, val in enumerate(nums):
            if target - val not in records:
                records[val] = idx
            else:
                return idx, records[target-val]

*enumerate()功能:

  • enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
  • 举例:
例1:
nums = ['one', 'two', 'three', 'four']
for index,value in enumerate(nums):
	print(index, value)


0 one
1 two
2 three
3 four
例2:
nums = {
    'a': 'one',
    'b': 'two',
    'c': 'three',
    'd': 'four'
}
for i, j in enumerate(nums):
    print(i, j)

0 a
1 b
2 c
3 d
例3:
nums = {
    'a': 'one',
    'b': 'two',
    'c': 'three',
    'd': 'four'
}
for i, j in enumerate(nums.values()):
    print(i, j)

0 one
1 two
2 three
3 four
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值