版权声明:版权归个人所有,未经博主允许,禁止转载 https://blog.csdn.net/danspace1/article/details/85912417
原题
https://leetcode.com/problems/two-sum/
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].
解题思路
建立一个字典, 遍历列表, 将值和索引存放到字典中, 每次读取数字n时, 检查target - n是否在字典中, 如果在, 返回对应的索引值.
时间复杂度: O(n)
空间复杂度: O(1)
代码
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
d = dict()
for idx, num in enumerate(nums):
if target - num in d:
return [d.get(target-num), idx]
d[num] = idx