有关哈希表的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]
网友评论