June 27, 2019 Two Sum <Easy>
- 题解一:Two-pass Hash Table
思路:目标是查找序列里符合条件的值的index,而Hash Table是映射数组里值和index的最好的方法,因此需使用Hash Table,使时间复杂度为O(1), 当发生碰撞时,时间复杂度为O(n).
步骤:使用两次迭代。(Runtime 40ms, Memory 15MB)
第一次迭代将每一个Value和它的Index送入Table。以Value做键值,Index做table的Value
第二次迭代检查 (target - nums[i]) 是否在Table中。
Java 有现成的HashMap类去实现Hash Table,Python怎么做?字典!
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
Map = {v: i for i, v in enumerate(nums)}
for i in range(len(nums)):
complement = target - nums[i]
if complement in Map and Map[complement] != i:
return [i, Map[complement]]
- 题解二: