leekcode #1两数之和(简单)

题目

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例

给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

传统遍历思想(二重循环,超时)

nums = [1, 2, 3, 4]
target = 5
i = 0
res = []
while i < len(nums):
    j = i + 1
    while j < len(nums):
        if nums[i] + nums[j] == target:
            res.append("这是一组:")
            res.append(i)
            res.append(j)
        j += 1
    i += 1
print(res)

优化遍历(一重循环,通过)

nums = [2,7,11,15]
target = 9
res = [] #结果显示列表
i = 0 #定义列表索引
new_nums = nums.copy() #复制新列表进行操作
while i < len(nums): #遍历列表
    new_nums.pop(i) #新列表删除索引i的元素
    #print(new_nums)
    if (target - nums[i]) in new_nums: #判断目标数减索引数是否在除去索引数的新列表中
        res.append(i) #结果列表中添加i的索引
        res.append(new_nums.index((target - nums[i]))+ 1) #新列表比原列表少1,且遍历从前到后,则(target - nums[i])的索引一定在i之后,添加(target - nums[i])索引
        break #中断循环,找到两个整数符合题意要求
    i += 1
    new_nums = nums.copy() # 原列表重新进行复制,进入下一次循环操作
    #print(new_nums)
print(res)
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容