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.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
Analyze:
- 注意题目里的假设:each input would have exactly one solution,因此输出答案是唯一的,不会出现[ 3, 4, 5, 6 ]这样的数组:(3+6 = 4+5 = 9),所以优先考虑的是一次遍历。
- 在一次遍历的同时,我们可以计算出这个数需要的另一个加数,记为checkNum,例如5的checkNum就是(9-5=)4。
- 判断当前数字是否在checkNum中,例如遍历到数字4的时候,发现有checkNum中恰好有一个4,则成功找到。
这里的难点就在于如何返回checkNum对应那个数字的下标,解决办法是:
创建一个solution_dict字典,字典的key是checkNum,value是当前数字在nums中的下标
Code:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
solution_dict = {}
for i in range(len(nums)):
if (nums[i] in solution_dict): # if already exists
return [solution_dict[nums[i]],i]
else: # renew the dictionary
# calcu what we need
checkNum = target - nums[i]
solution_dict[checkNum] = i
Result:
Runtime: 40 ms, faster than 86.49% of Python3 online submissions for Two Sum.
Memory Usage: 14.5 MB, less than 5.08% of Python3 online submissions for Two Sum.