1.Two Sum

本文解析了经典的两数之和问题,通过两种不同的Python实现方法达到O(n)的时间复杂度,介绍了如何利用字典来优化查找过程。

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

题目表述和我的答案:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
这道题比较简单,基本思路就是对一个列表循环两次,在过程中进行比较,得到与target值相等的两个索引返回。
def twoSum(nums, target):
    """
    :type nums: List[int]
    :type target: int
    :rtype: 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

遇到的问题:

1.pythonfor循环数组的索引的使用:Range(i) 表示从0i-1的索引定义一个list 直接使用nums = [2, 3, 4, 5]不用使用list什么的,因为python自动识别类型。

2.报错twoSum() missing 1 required positional argument: 'target'这个问题怎么解决,python函数使用的问题是因为leetcode中答案中的代码自带了一个self参数(定义了一个class),而在我们这里只需要两个函数,所以会提示缺少一个需要的参数。

Discuss:

找到python实现的O(n)复杂度的代码。

def twoSum(self, nums, target):
        if len(nums) <= 1:
            return False
        buff_dict = {}
        for i in range(len(nums)):
            if nums[i] in buff_dict:
                return [buff_dict[nums[i]], i]
            else:
                buff_dict[target - nums[i]] = i

字典是个好东西,要学会用。。

创建一个空字典,键用target-num[i]标记,值用索引来表示。

当列表中遇到跟键里面相同的,输出buff_dict[nums[i]]和i,很巧妙。




评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值