1. 題目
給定一個整數數組 nums 和一個目標值 target,請你在該數組中找出和為目標值的那 兩個 整數,并返回他們的數組下標。
你可以假設每種輸入只會對應一個答案。但是,你不能重復利用這個數組中同樣的元素。
示例:
給定 nums = [2, 7, 11, 15], target = 9
因為 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
2. 解題思路
2.1 樸素解法(暴力遍歷)
通過兩次循環,每次循環遍歷列表,這種算法的時間復雜度是 O(n^2)
2.2 哈希存儲
思路:利用hash表,key:當前值,value:索引
解題方法:遍歷數組時,查詢hash表中,是否存在target - nums[i]。
若有,返回當前索引和存在的key的value;
若不存在,則將當前值和索引存入hash表中
python中的字典就是天然hash表;c++中的unorder_map;
Java中HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();
代碼如下:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
nums_hash = {}
for each in range(len(nums)):
dif = target - nums[each]
if dif in nums_hash:
return [nums_hash[dif], each]
else:
nums_hash[nums[each]] = each
3. 總結/分類
數據結構的巧妙利用