--- tags: LeetCode, Python --- # 1. TwoSum ## Desctiprion Given an array of integers `nums` and an integer `target`, return *indices of the two numbers such that they add up to `target`*. You may assume that each input would have ***exactly* one solution**, and you may not use the *same* element twice. You can return the answer in any order. **Example 1:** ```python Input: nums = [2,7,11,15], target = 9 Output: [0,1] Output: Because nums[0] + nums[1] == 9, we return [0, 1]. ``` **Example 2:** ```python Input: nums = [3,2,4], target = 6 Output: [1,2] ``` **Example 3:** ```python Input: nums = [3,3], target = 6 Output: [0,1] ``` # Code: 為了提高我們的運行時復雜度,我們需要一種更有效的方法來檢查數組中是否存在補碼。 如果補集存在,我們需要查找它的索引。 維護數組中每個元素到其索引的映射的最佳方法是什麼? 一個哈希表。 我們通過空間換取速度,將查找時間從 O(n) 減少到 O(1)。 哈希表正是為此目的而構建的,它支持在近乎恆定的時間內快速查找。 我說“接近”是因為如果發生碰撞,查找可能退化到 O(n) 時間。 但是只要仔細選擇散列函數,在散列表中查找就應該分攤 O(1) 時間。 一個簡單的實現使用兩次迭代。 在第一次迭代中,我們將每個元素的值及其索引添加到表中。 然後,在第二次迭代中,我們檢查每個元素的補碼 (target−nums[i]) 是否存在於表中。 請注意,補碼不能是 nums[i] 本身! ```python hash_table = {} for i, num in enumerate(nums): if target - num in hash_table: return([hash_table[target - num], i]) break # 看到有人在這加了break, 理論上不會執行到, 但時間卻會比較短 hash_table[num] = i return([]) ``` Notes: 邊創Hash Table, 邊看是否達到解答, 達到就返回