Problem: 1. 两数之和
思路
n方可以暴力,也可以用hash去降低时间复杂度。
解题方法
遍历列表,每个数都看一下是否它的补是否再hash表里面,在就说明找到了,不在就把它放进去,然后继续遍历。
复杂度
时间复杂度:
添加时间复杂度, 示例: O ( n ) O(n) O(n)
空间复杂度:
添加空间复杂度, 示例: O ( n ) O(n) O(n)
Code
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashTable = dict();
for i in range(len(nums)):
if target - nums[i] in hashTable:
return [hashTable[target - nums[i]], i]
else:
hashTable[nums[i]] = i