(python版) Leetcode-1.两数之和

01 题目:两数之和

链接:https://leetcode-cn.com/problems/two-sum
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

示例:

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

02 解析

  • 暴力法:双循环 时间复杂度为O(n2) 超时不予讨论
  • hash法:hash表将循环过的值,只要对比在不在表中,所以nums只要遍历一次,时间复杂度为O(n)
    another_num 是把另一个数求出来,在hashmap中查找
    Line 17:hashmap字典 保存的key值是num,value值是index
    以输入twoSum([2,7,11,15,14],26)为例: 我们在遍历到11的时候,hashmap中没存15的值,所以到15的时候,才能找到hashmap中有11值,符合要求,才return

这也是为什么return的 hashmap[another_num] 在前, index 在后!
another_num是已存在hashmap中的,所以在前面(小的下标),index只能是后面遍历到的数(大的下标)

03 代码

# 1.暴力法
# def twoSum(nums, target):    
#     for i in range(len(nums)):
#         for j in range(i+1,len(nums)):
#             if nums[i] + nums[j] == target:
#                 return [i,j]
#     return []

# 2.hash表
def twoSum(nums, target):
    hashmap = {}
    for index,num in enumerate(nums):	# 遍历nums
        another_num = target-num   	 	# 另一个数
        if another_num in hashmap:
            print("find it! Now index=%d,num=%d,another_num=%d"%(index,num,another_num))
            return [hashmap[another_num],index]
        hashmap[num] = index
        print(hashmap)
    return None
right_index = twoSum([2,7,11,15,14],26)
print(right_index)
输出:
{2: 0}
{2: 0, 7: 1}
{2: 0, 7: 1, 11: 2}
find it! Now index=3,num=15,another_num=11
[2, 3]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值