哈希表
其他语言版本
1. 两数之和
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。你可以按任意顺序返回答案。
题解
该题目的关键在于遍历循环数组,在遍历的过程中,记录目前值与target的差值,且使用map记录差值情况,若存在差值,则直接返回差值
def two_sum(nums: list[int], target: int) -> list[int]:
hash_map = {}
for i, num in enumerate(nums):
# 计算当前值与target的差值
target_new = target - num
if target_new in hash_map:
# 如果存在该差值,则直接返回 [该差值的下标, 与当前值的下标]
return [hash_map[target_new], i]
else:
# 暂时不存在差值,存入当前值的下标
hash_map[num] = i
return [0, 0] # 如果没有找到任何符合条件的数对,返回 [0, 0](或者你可以选择抛出异常)
# arr = two_sum([3, 2, 4], 6)
# print(arr) # [1, 2]
2. 字母异位词分组
给你一个字符串数组,请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。
字母异位词 是由重新排列源单词的所有字母得到的一个新单词。
题解
该题目在于将每一项数据根据Unicode编码排序,异位词经过排序后的字符串会相等,后使用map记录数据即可。
def groupAnagrams(strs: list[str]) -> list[list[str]]:
# 使用字典来存储排序后的字符串作为键,原字符串列表作为值
hash_map = {}
# 遍历输入的字符串列表
for s in strs:
# 将字符串转换为字符列表,然后排序,再转换回字符串
sorted_str = ''.join(sorted(s))
# 如果排序后的字符串已存在于字典中,则添加当前字符串到列表中
if sorted_str in hash_map:
hash_map[sorted_str].append(s)
else:
# 否则,在字典中创建一个新条目,列表中包含当前字符串
hash_map[sorted_str] = [s]
# 将字典的值(即所有字符串列表)收集到结果列表中
res = list(hash_map.values())
return res
# strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
# print(groupAnagrams(strs))
# 输出: [['eat', 'tea', 'ate'], ['tan', 'nat'], ['bat']]
3.最长连续序列
给定一个未排序的整数数组 nums ,找出数字连续的最长序列(不要求序列元素在原数组中连续)的长度。
请你设计并实现时间复杂度为 O(n) 的算法解决此问题。
链接
题解:
def longestConsecutive(nums: list[int]) -> int:
# 去重
num_set = set(nums)
# 记录当前最长连续序列长度
longest_streak = 0
for num in num_set:
# 如果不存在比当前值小1的值,则当前值作为起点
if num - 1 not in num_set:
current_num = num
current_streak = 1
# 遍历,找比当前值大1的数
while current_num + 1 in num_set:
current_num += 1
current_streak += 1
# 更新最大长度
longest_streak = max(longest_streak, current_streak)
return longest_streak
# nums = [100, 4, 4, 200, 1, 3, 2]
# print(longestConsecutive(nums)) # 输出: 4
指针
4.移动零
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作。
题解
def moveZeroes(nums: list[int]) -> list[int]:
if len(nums) == 1:
return nums
left = 0
for right in range(len(nums)):
if nums[right] != 0:
# 右边不等于0
if nums[left] == 0:
# 左边等于0,则交换左右两边的元素
nums[left], nums[right] = nums[right], nums[left]
# 找到了右边不等于0的目标元素,移动左指针
left += 1
return nums
# arr = moveZeroes([0, 1, 0, 3, 12])
# print(arr) # 输出: [1, 3, 12, 0, 0]
5.盛水最多的容器
给定一个长度为 n 的整数数组 height 。有 n 条垂线,第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) 。
找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。返回容器可以储存的最大水量。
说明:你不能倾斜容器。
题解
左右指针法,每次移动短的指针能才有机会使容纳的水变多,因为左右指针收窄时,形成的容器的底是变小的,而能存多少水,容器的高也是一个决定性因素,根据木桶原理,短的木板决定水桶能装多少水,在底变小的情况下,移动短的指针有机会遇到更长的木板,使得容积变大。移动过程中,更新最大值即可。
def maxArea(height: list[int]) -> int:
left: int = 0
right: int = len(height) - 1
res: int = 0
while left < right:
# 底
bottom: int = right - left
# 高
h: int = min(height[left], height[right])
# 更新最大值
res = max(res, bottom * h)
# 根据两边的高度移动指针
if height[left] > height[right]:
right -= 1
else:
left += 1
return res
# num: int = maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7])
# print(num) # 输出: 49
关注我的公众号,回复 100905A1 获取hot100算法在线链接