leetcode之 两数之和

# -*- coding: utf-8 -*-
# @Time : 2018/9/27 21:41
# @Author : cxa
# @File : twonum.py
# @Software: PyCharm

# 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
# 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
# 示例:
# 给定 nums = [2, 7, 11, 15], target = 9
# 因为 nums[0] + nums[1] = 2 + 7 = 9
# 所以返回 [0, 1]
'''
分析:
直接理解不太好理解换个更简单的思路,把题目返回这两个值
此时就变得简单多了 代码如下:
'''
num = [2, 7, 11, 15, 5, 4]
target = 9
l = len(num)
d = {}

for i in range(l):
    v = target - num[i]
    # if num[i] in d: # 如果键值num[i]已经存在了,说明之前的数字为循环过的了,肯定是存在于列表的
    #     print(d[num[i]], num[i])#索引可以打印出两个符合条件的数
    #     print(num.index(d[num[i]]), num.index(num[i]))#这一步就可以获取索引了。
    if num[i] in d:  # 如果键值num[i]已经存在了,说明之前的数字为循环过的了,肯定是存在于列表的
        print(d[num[i]], i)  # 索引可以打印出两个符合条件的数
    else:
        # d[v] = num[i] #减后的值为字典的键,当前的值为字典的值。即当前的减数为哪个数减出来的,
        d[v] = i
        # 因为需要返回索引索引改为值为索引,即当前的减数为哪个数的索引。
原文地址:https://www.cnblogs.com/c-x-a/p/9716023.html