标签:type https iss 利用 ict put 遍历 runtime inpu
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].
虑一个整数列表,返回两个数字的索引,使得这两个整数之和等于给定的目标值。假定每个输入有唯一解,且每个元素不能重复使用。
举例:给定列表 nums = [2,7,11,15], 目标 target = 9, 返回 [0,1].
nums = [2,7,11,15]
target = 9
- 开始
- 定义空字典 hash_dict = {}
-- 遍历列表nums
-- 遍历到第一个数2,检查是否在hash_dict中;发现不在
-- 则,存储target-2(目标值与当前值的差),0(当前值的索引)到字典中;此时hash_dict = {7:0}
-- 遍历到第二个数7,检查是否在hash_dict中;发现在
-- 则,输出[hash_dict[7],1],即[0,1]
- 结束
这种方式的关键在于应用字典,将每次遍历的整数所需要的另一个数记录下来,同时也记录下当前整数的索引,在之后的遍历中,一旦找到这个整数,即可得到需要的两个索引,省去了两层循环的嵌套搜索。
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hash_dict = {}
for i in range(len(nums)):
if nums[i] in hash_dict:
return [hash_dict[nums[i]],i]
else:
hash_dict[target - nums[i]] = i
标签:type https iss 利用 ict put 遍历 runtime inpu
原文地址:https://www.cnblogs.com/initial-h/p/9278205.html