Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
1、暴力解法:利用两层循环,比如i从0:len(nums),j从i+1:len(nums),如果i + j == target,则说明找到了,返回i和j,否则返回空。但复杂度为$ o\left( n^2 \right) $
2、用字典模拟哈希求解,遍历列表同时查字典。复杂度为$ o(n) $
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dic = {}
for index, val in enumerate(nums):
m = target - val
if m in dic:
return(dic[m], index)
else:
dic[val] = index
原文:https://www.cnblogs.com/yuzhou-1su/p/11755795.html