LC 两数之和(哈希表)
1 两层循环
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
length = len(nums)
i = 0
while i < length:
for j in range(i+1,length):
if nums[i]+nums[j] == target:
return [i,j]
i += 1
2 哈希表
一次循环
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
length = len(nums)
dic = dict({})
for i in range(length):
if target - nums[i] in dic:
return [i, dic[target - nums[i]]]
else:
dic[nums[i]] = i