006_Python列表练习_案例_两数之和

给定:一个整数数组nums = [2, 7, 11,15], 目标值target = 9
因为:在该数组中找出和为目标值的两个整数–>mums[0] + nums[1] = 9
输出:返回它们的数组下标 [0, 1]

方法1:分支流程控制、循环流程控制 + 常用方法s.index 方法 + 列表遍历for num in nums + 注意: 不要使用双层for 循环实现, 可以成功, 但时间复杂度高,不建议。

def fun(nums, target):
    res = []
    # 1. 遍历数组中的元素
    for num in nums:
        # 2.如果加数(num)大于和,不做任何操作,执行下次for循环即可
        if num <= target:
            # 3. 加数(num)小于和,确定另一个加数(other_num)
            other_num = target - num
            # 4. 判断另一个加数(other_num)是否在数组nums中
            if other_num in nums:
                flag1 = nums.index(num)
                flag2 = nums.index(other_num)
                # 5. 确保2+7=9 和 7+2=9 的情况只存储最开始的一种即可
                if [flag1, flag2] not in res and [flag2, flag1] not in res:
                    res.append([flag1, flag2])
    # 6. 遍历打印结果列表中的元素
    for item in res:
        print(item)


if __name__ == "__main__":
	nums = [2, 7, 11, 15]
    target = 9
    fun(nums, target)

执行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值