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)

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

发布了37 篇原创文章 · 获赞 0 · 访问量 5334

猜你喜欢

转载自blog.csdn.net/qq_21156327/article/details/103408527