LeetCode 1 两数之和 Two Sum Python
2019-05-08 本文已影响0人
划水型派大星
有关哈希表的LeetCode做题笔记,Python实现
1. 两数之和 Two Sum
第一种方法:用哈希表,时间复杂度是O(n)
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dic = {}
for i in range(len(nums)):
if nums[i] in dic:
return [dic[nums[i]], i]
else:
dic[target - nums[i]] = i
第二种方法:暴力两重遍历,这样时间复杂度是O(n^2)
,在LeetCode里提交会超时
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]