Leetcode:两数之和

本文详细解析了LeetCode经典题目“两数之和”的三种解法,包括双层循环、列表辅助查找和字典高效求解,对比了各种方法的时间复杂度和效率。

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

Leetcode:两数之和


给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。。
示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9  所以返回 [0, 1]


第一种方法:
  • 我先遍历两次,然后为了防止重复使用数字,判断下标是否相等,如果不相等在返回。虽然这个方法行得通,但是非常耗时间! 不推荐此方法!!!
nums = [2, 7, 11, 15]
target = 9

def answer(nums, target):
    for index, num in enumerate(nums):
        for other_index, other_num in enumerate(nums):
            if other_num == target - num:
            	# 防止重复使用
                if index != other_index:
                    return index, other_index
                    
a = answer(nums, target)
print(a)

第二种方法:
  • 这个方法是先定义一个空列表,在遍历原有列表,把遍历的下标和值加进空列表,从里面找匹配的! 这个方法比第一种方法好!
nums = [2, 7, 11, 15]
target = 9


def answer(nums, target):
    n_list = []
    for index, num in enumerate(nums):
        another_num = target - num
        if another_num in n_list:
            return n_list.index(another_num), index
        n_list.append(num)
    return None
    
a = answer(nums, target)
print(a)

(推荐)第三种方法:
  • 先定义一个字典,在遍历列表,把遍历的下标和值加进字典,从字典里面找答案!
nums = [2, 7, 11, 15]
target = 9

def answer(nums, target):

	# 创建一个字典,每次把遍历的数字加进去
    another_nums = {}
    # 利用enumerate,把索引和值遍历出来
    for index, num in enumerate(nums):
        another_num = target - num
        if another_num in another_nums:
            return another_nums[another_num], index
        another_nums[num] = index
    return None

a = answer(nums, target)
print(a)


这是个人在学习过程中遇到的问题和方法,不喜勿喷!!!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值