1.題目
給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和爲目標值的那 兩個 整數,並返回他們的數組下標。
1.1 示例
給定 nums = [2, 7, 11, 15], target = 9
因爲 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
2.思路
2.1 把數組nums中的整數通過for循環放到字典中
2.2 通過目標值和數組,在字典中進行查找
2.3 判斷空、重複的情況
3.題解
def twoSum(nums, target):
hashmap = {}
# 2.1 把數組nums中的整數通過for循環放到字典中
for idx, num in enumerate(nums):
hashmap[num] = idx
# 2.2 通過目標值和數組,在字典中進行查找
for i,num in enumerate(nums):
j = hashmap.get(target - num)
# 2.3 判斷空、重複的情況。
if j is not None and j != i:
return [i,j]
# 測試
print(twoSum([2, 7, 11, 15], 9))
4.耗時
運行時間:60 ms
內存消耗:15.6 MB