Leetcode刷题(19) 哈希表老辅助了
在数组问题中,哈希表常常可以用空间复杂度换时间复杂度
1. 两数之和
参考labuladong的TwoSum问题的核心思想
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
n = len(nums)
index2num = dict()
for i in range(n):
# num-->index
# 构造一个哈希表:元素映射到相应的索引
index2num[nums[i]] = i
for i in range(n):
# 得到nums[i]的目标数j
j = target - nums[i]
# j在表中且index和i不一样(不是同一个数)
if j in index2num.keys() and index2num[j] != i:
return [i, index2num[j]]
560. 和为K的子数组
方法参考labuladong的https://labuladong.gitbook.io/algo/suan-fa-si-wei-xi-lie/qian-zhui-he-ji-qiao
class Solution(object):
def subarraySum(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
ans = 0
n = len(nums)
# 用preSum记录前缀和--->该前缀和的次数
preSum = dict()
# 第一个数的前缀和是0
sum0_i = 0
preSum[sum0_i] = 1
for i in range(n):
# 循环累加, 计算得到当前的前缀和
sum0_i += nums[i]
sum0_j = sum0_i - k
# 更新ans
if sum0_j in preSum.keys():
ans += preSum[sum0_j]
# 更新前缀和的字典
preSum[sum0_i] = preSum.get(sum0_i, 0) + 1
return ans
448. 找到所有数组中消失的数字
参考labuladong的如何同时寻找缺失和重复的元素
# 原地修改方法
class Solution(object):
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
n = len(nums)
res = []
# 在心里想其实num是和index一一对应的
# 做一个映射num-1 --> index
for i in range(n):
# 如果大于0表示没有访问过,便修改这个下表下的数字表示已经有nums[i]了
index = abs(nums[i]) - 1
# 遇到重复的数字的话, 由于nums[index] > 0已经小于0了所以不会再*-1重返正数
if nums[index] > 0:
nums[index] *= -1
for i in range(n):
# i下面的数还大于0说明i+1在nums中是没有的
if nums[i] > 0:
res.append(i + 1)
return res
645. 错误的集合
class Solution(object):
def findErrorNums(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
n = len(nums)
# 先初始化重复的元素为-1
dup = -1
for num in nums:
# 得到其映射的索引 nums [1, 2, 3, 4] --> indexes [0, 1, 2, 3]
# 因为num可能被修改为负数了所以要用abs()
index = abs(num) - 1
if nums[index] < 0:
# 因为num可能被修改为负数了所以要用abs()
dup = abs(num)
else:
nums[index] *= -1
# 先初始化缺失的元素为-1
mis = -1
for i in range(n):
# 该数大于0说明没有被访问到
# 其对应的索引就是mis - 1
if nums[i] > 0:
mis = i + 1
return [dup, mis]