1. 題目描述
給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和爲目標值的那 兩個 整數,並返回他們的數組下標。
你可以假設每種輸入只會對應一個答案。但是,數組中同一個元素不能使用兩遍。
示例:
給定 nums = [2, 7, 11, 15], target = 9
因爲 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
2. 解題思路
選取數組 nums
中的第一個數 num
,用 target
減去,得到 another_num
,即 num +another_num = target
,在剩餘的數中尋找 another_num
,如果存在,返回兩個數的索引。依次遍歷整個數組。
基本思路是這樣,但在 “在剩餘的數中尋找num2” 這一步,尋找算法的好壞直接影響整體算法的效率。
因爲數組中同一個元素不能使用兩遍,這就在於 “在剩餘的數中尋找num2” 中的 “剩餘” 怎麼實現了,不能簡單地使用 if another_num in nums
,需要將尋找的 num
從查找數組 nums
中剔除,這樣查找數組纔是剩餘的。
3. 代碼
3.1暴力查找
外循環確定 num
,內循環查找 another_num
,由於內循環從 i+1
開始,保證了查找數組中不包含 num
。
但暴力查找效率極低。
def twoSum0(nums, target):
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i] + nums[j] == target:
return [i,j]
3.2 哈希表查找
保持數組中的每個元素與其索引相互對應的最好方法是什麼?哈希表。
用字典模擬哈希表。
使用 enumerate()
函數獲取 nums
列表元素和對應索引,並將 another_num
及其對應的索引存入字典,在原列表 nums
裏遍歷 num
,在字典裏尋找對應 another_num
。
def twoSum1(nums, target):
hashmap = {}
for index, num in enumerate(nums):
another_num = target - num
if another_num in hashmap:
return [hashmap[another_num], index]
else:
hashmap[num] = index
return None