给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
a + b = target
也可以看成是
a = target - b
在map整数整数的序号中,可以查询到a的序号。这样就不用嵌套两个for循环了。
func twoSum(nums []int, target int) []int {
m := make(map[int]int, len(nums))
for i, b := range nums {
if j, ok := m[target-b]; ok {
return []int{j, i}
}
m[nums[i]] = i
}
return nil
}
class Solution:
def twoSum(self, nums, target):
if len(nums) <= 1:
return False
d = dict()
for i in range(len(nums)):
if nums[i] in d:
return [d[nums[i]], i]
else:
d[target - nums[i]] = i
恩,最后找队友一起刷题。喜欢可以联系我 ,来公众号“Python爬虫与算法进阶”找我哦
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有