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=2python
一、暴力解法:利用两层循环,好比i从0:len(nums),j从i+1:len(nums),若是i + j == target,则说明找到了,返回i和j,不然返回空。less
复杂度分析:时间复杂度为 $ o\left( n^2 \right) $ ,空间复杂度 $ o(1) $code
二、对暴力解法进行改进,已知target,因此其实只须要遍历一遍i就行,查看j == target - i是否在字典中。查找的话能够利用到hashmap,用字典模拟哈希求解,遍历列表同时查字典。blog
复杂度分许:时间复杂度为 $ o(n) $ ,空间复杂度也为 $ o(n) $ci
def twoSum_baoli(nums, target): length = len(nums) if length < 2: return None for i in range(length): for j in range(i+1, length): if nums[i] + nums[j] == target: return [i, j] return None
def twoSum(nums, target): hash_map = dict() for i, x in enumerate(nums): if target - x in hash_map: return [i, hash_map[target - x]] hash_map[x] = i