版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/HappyRocking/article/details/82287984
题目
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
给定一个整数的数组,返回两个元素的下标,这两个元素相加等于一个给定值。
可以假设每一个输入都只有一种答案。
示例:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
思路
1、 暴力求解
双重循环,枚举所有可能的整数对,判断相加是否为给定值。
所有整数对的个数为
,因此算法复杂度为
2、动态规划
每扫描到一个元素 a
,便将 target -a
作为 key 存入到一个词典中(词典的 value 为数组的下标,记录位置)。
这样,下次一旦扫描到了 target-a
,且词典中恰好有这个值,这说明之前已经遍历过 a
,这两个数之和正好为 target
, 因此这两个数为所求。
因为只需要遍历一次,所以算法复杂度为
代码
# -*- coding: utf-8 -*-
def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
match_idx_dict = dict() # key=差值,value=下标
for i in range(len(nums)):
num = nums[i]
if num not in match_idx_dict:
match_idx_dict[target-num] = i
else:
return [match_idx_dict[num], i]
return None
if '__main__' == __name__:
nums = [2, 7, 11, 15]
target = 9
print(twoSum(nums, target))