前言
题单LeetCode 热题 100的哈希部分,给出解析。
1. Two Sum
题目描述
Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target
.
You may assume that each input would have exactly one solution , and you may not use the same element twice.
You can return the answer in any order.
Constraints:
2 <= nums.length <= 10^4
-10^9 <= nums[i] <= 10^9
-10^9 <= target <= 10^9
- Only one valid answer exists.
Follow-up: Can you come up with an algorithm that is less than O(n^2)
time complexity?
解题方法
使用一个哈希表存储数组中的元素及其索引。
key: 元素值;
value: 元素索引。
循环遍历数组,计算 target
与当前元素的差值,检查哈希表中是否存在差值,如果哈希表中存在差值,返回两个元素的索引。
如果没有找到差值,就将当前元素及其索引存入哈希表,继续遍历。
代码实现
Python版本:
1 | class Solution: |
Java版本:
1 | class Solution { |
复杂度分析
时间复杂度:$O(n)$,仅需遍历一次数组。
空间复杂度:$O(n)$,哈希表带来的额外存储空间。
49. Group Anagrams
题目描述
Given an array of strings strs
, group the anagrams together. You can return the answer in any order .
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Constraints:
1 <= strs.length <= 10^4
0 <= strs[i].length <= 100
strs[i]
consists of lowercase English letters.
解题方法
要将给定的字符串数组按照字母异位词分组,可以利用字母异位词的一个性质:它们排序后会得到相同的字符串。基于此,我们可以将每个字符串排序后作为键,将其所有字母异位词放在同一个列表中,最后返回这些列表。
思路:
- 创建一个哈希表:
- key: 排序后的字符串;
- value: 包含这些字母异位词的列表。
- 遍历字符串数组,对每个字符串进行排序,将排序后的字符串作为键,将原字符串添加到对应的列表中。
- 返回哈希表中所有值的列表。
代码实现
Python版本:
1 | class Solution: |
Java版本:
1 | class Solution { |
复杂度分析
时间复杂度:$O(nmlogm)$,其中 $n$ 为 $strs$ 的长度,$m$ 为 $strs[i]$ 的长度。
空间复杂度:$O(nm)$,哈希表带来的额外存储空间。
128. Longest Consecutive Sequence
题目描述
Given an unsorted array of integers nums
, return the length of the longest consecutive elements sequence.
You must write an algorithm that runs in O(n)
time.
Constraints:
0 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
解题方法
这个问题要求我们在给定的未排序整数数组中,找到最长的连续元素序列的长度,并且算法的时间复杂度为 O(n)
。
解决思路:
使用集合(Set)存储数组中的元素:
通过将所有元素存储在集合中,我们可以在O(1)
的时间内判断一个元素是否存在。遍历数组:
对于数组中的每一个数字,检查它是否是某个连续序列的起点。一个数字是序列的起点,当且仅当它的前一个数字(num - 1
)不在集合中。计算连续序列的长度:
如果找到一个序列的起点,继续检查这个起点之后的连续数字是否存在,并计算这个序列的长度。更新最大长度:
在遍历过程中,记录遇到的最长序列的长度。返回最长长度:
遍历完成后,返回记录的最长序列的长度。
代码实现
Python版本:
1 | class Solution: |
Java版本:
1 | class Solution { |
复杂度分析
时间复杂度:$O(n)$,只需遍历一次序列。
空间复杂度:$O(n)$,哈希表带来的额外存储空间。