Tag
【自定义哈希】【哈希表】【数组】
题目来源

题目解读
将字符串数组中互为字母异位词的字符串组合在一起,并返回最后的结果列表,返回形式见函数的返回值。
解题思路
方法一:排序+哈希表
如果两个字符串互为字母异位词,那么它们按照相同的排序方式(都按照升序或者降序)进行排序之后,得到的字符串是一样的。根据这一点,我们将字符串进行升序排序后的字符串作为键,原字符串作为值的一部分,存放在 unordered_map
中。具体来说,定义的 map
,如下所示:
unordered_map<string, vector<string>> str2StrVec;
unordered_map
的键为排序后的字符串,值为互为异位词的字符串组成的数组。
无序哈希表值组成的数组就是我们最终的答案。
实现代码
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> str2StrVec;
for (string str : strs) {
string tmpStr = str;
sort(tmpStr.begin(), tmpStr.end());
str2StrVec[tmpStr].push_back(str);
}
vector<vector<string>> res;
for (auto [_, strVec] : str2StrVec) {
res.push_back(strVec);
}
return res;
}
};
复杂度分析
时间复杂度:
n
k
l
o
g
k
nklogk
nklogk,
n
n
n 为字符串数组 strs
的长度,
k
k
k 为 strs
中字符串的最大长度。
空间复杂度: n k l o g k nklogk nklogk。
方法二:数组作为哈希表的键
在方法一中,我们使用的是排序后的字符串作为无序哈希表的键,我们也可以使用 使用数组模拟哈希表 中提到的哈希数组作为键。
具体地,如果两个字符串互为异位词,那么两字符串中出现的字符数量应该是相等的。
字符串中出现的字符都是小写字母,因此我们可以使用长度为 26
的数组 cnts
来表示每个字符出现的次数。
我们把字符对应到下标上,比如字符 'a'
对应数组中的下标为 0
,字符 'b'
对应数组中的下标为 1
,…,字符 'z'
对应数组中的下标为 25
。下标对应的值为该字符出现的次数,比如 cnts[1] = 2
表示字符串中字符 b
出现 2
次。
问题
不能使用 vector<>
数组作为 unorderd_map
的键。也不能使用 pair<>
作为
使用 array<>
会怎么样呢?官方解法 方法二 中的 C++
代码就是利用的自定义对 array<int, 26> 类型的哈希函数。
经过实测之后,利用官方题解中的自定义哈希函数以及 vector<>
之后,代码依然是可以通过的,稍后我会把代码贴出来。
其实 vector<>
和 array<>
不能直接作为 unordered_map
的键的原因是哈希表重复问题,因此需要我们自定义哈希映射,也就是哈希函数。官方题解中借助的是一个 std::hash<int>
类型的哈希函数对象,用于将 int
类型的值哈希成 size_t
,然后借助 accumulate<>
来将 array<int, 26>
累加起来(异或和),实现自定义哈希函数。
官方的自定义哈希+array<int, 26>代码
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
// 自定义对 array<int, 26> 类型的哈希函数
auto arrayHash = [fn = hash<int>{}] (const array<int, 26>& arr) -> size_t {
return accumulate(arr.begin(), arr.end(), 0u, [&](size_t acc, int num) {
return (acc << 1) ^ fn(num);
});
};
unordered_map<array<int, 26>, vector<string>, decltype(arrayHash)> mp(0, arrayHash);
for (string& str: strs) {
array<int, 26> counts{};
int length = str.length();
for (int i = 0; i < length; ++i) {
counts[str[i] - 'a'] ++;
}
mp[counts].emplace_back(str);
}
vector<vector<string>> ans;
for (auto it = mp.begin(); it != mp.end(); ++it) {
ans.emplace_back(it->second);
}
return ans;
}
};
我的自定义哈希+vector<int>代码
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
// 自定义对 array<int, 26> 类型的哈希函数
auto arrayHash = [fn = hash<int>{}] (const vector<int>& arr) -> size_t {
return accumulate(arr.begin(), arr.end(), 0u, [&](size_t acc, int num) {
return (acc << 1) ^ fn(num);
});
};
unordered_map<vector<int>, vector<string>, decltype(arrayHash)> mp(0, arrayHash);
for (string& str: strs) {
vector<int> counts(26, 0);
int length = str.length();
for (int i = 0; i < length; ++i) {
counts[str[i] - 'a'] ++;
}
mp[counts].emplace_back(str);
}
vector<vector<string>> ans;
for (auto it = mp.begin(); it != mp.end(); ++it) {
ans.emplace_back(it->second);
}
return ans;
}
};
复杂度分析
时间复杂度:
n
k
nk
nk,
n
n
n 为字符串数组 strs
的长度,
k
k
k 为 strs
中字符串的最大长度
空间复杂度: n k nk nk。
方法三:字符串作为哈希表的键
先来看实现代码:
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> res ;
map<string, vector<string>> str2StrVec ;
// 统计string的各字母频次,以频次为key直接加入队列
for (auto str : strs) {
string sts = string(26, '0') ;
for (auto c : str) ++ sts[c-'a'] ;
str2StrVec[sts].emplace_back(str) ;
}
for (auto [_, strVec] : str2StrVec) res.emplace_back(strVec) ;
return res;
}
};
我们把具有相同字符串 sts
的字符串 str
加入到 str2StrVec[sts]
中。需要注意的是这里的 sts
的更新方式:
- 初始化
sts
为26
个'0'
拼接而成; - 我们在
str
中每遇到一个字符c
,我们就将该字符对应的下标c - 'a'
在sts
中对应的值加一,对应的是sts
中的字符,对字符加一实际是对该字符对应的 ASCII \texttt{ASCII} ASCII 加一。
这时候需要注意 “碰撞” 的问题,因为 char
字符类型的上限自多能统计 256
个字符,如果超出了这个数量,那么出现 “哈希冲突”,即 不同的字符对应到了相同的字符上,也就是 “碰撞”。但是本题的当个字符串的数量不超过 100
,所以不会出现碰撞。
复杂度分析
时间复杂度:
n
k
nk
nk,
n
n
n 为字符串数组 strs
的长度,
k
k
k 为 strs
中字符串的最大长度
空间复杂度: n k nk nk。
知识回顾
accumulate
今天我们来看一个 C++
中的库函数 accumulate()
,通常我们使用该函数来计算数组内所有元素的和。
求和操作
我们要计算数组 numbers
中所有元素的和,代码如下:
#include <iostream>
#include <vector>
#include <numeric>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
int sum = std::accumulate(numbers.begin(), numbers.end(), 0);
std::cout << "Sum of elements: " << sum << std::endl;
return 0;
}
对应的类模板为:
template <class InputIterator, class T>
T accumulate (InputIterator first, InputIterator last, T init);
该类模板表示的含义是将迭代器 [first, last)
内的元素值加到 init
上,我们上述求和代码正是将 numbers
的首迭代器到尾后迭代器中的元素加到 0
上,从而实现了求和。
自定义二元操作
除了求和我们还可以自定义 “二元操作”,实现 accumulate
的其他 “累加” 操作。其对应的类模板为:
template <class InputIterator, class T, class BinaryOperation>
T accumulate (InputIterator first, InputIterator last, T init, BinaryOperation binary_op);
在本题的方法二中使用的就是 accumulate
的二元操作来计算 array<int, 26>
的哈希值的。
我们通过一个例子来理解 accumulate
的自定义二元操作:计算数组 nums = [12, 24, 36, 48]
中所有元素的最大公约数。先贴上利用 accumulate
自定义二元操作的代码:
#include <iostream>
#include <vector>
#include <numeric>
// 自定义的二元操作函数,计算两个整数的最大公约数
int gcd(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
int main() {
std::vector<int> numbers = {24, 36, 48, 60};
int result = std::accumulate(numbers.begin(), numbers.end(), 0, gcd);
std::cout << "GCD of elements: " << result << std::endl;
return 0;
}
在这个示例中,我们定义了一个名为 gcd
的自定义二元操作函数,它计算两个整数的最大公约数。然后,我们使用 std::accumulate
来计算数组 numbers
中所有元素的最大公约数。gcd
函数被传递给 std::accumulate
,以执行自定义的累积操作。
这个例子中自定义二元操作的底层逻辑如下代码所示,__init
初始为 0
。这段代码的含义是将数组 numbers
中的所有元素都与初始的值 0
进行求最大公约数,并返回。
for (; __first != __last; ++__first) {
__init = gcd(__init, *__first);
return __init;
}
学会了自定义二元操作之后,我们也可以通过它来实现求和操作,对应的代码为:
#include <iostream>
#include <vector>
#include <numeric>
int main() {
std::vector<int> numbers = {2, 4, 6, 60};
int sumVal = std::accumulate(numbers.begin(), numbers.end(), 0, [](int a, int b) {
return a + b;
});
std::cout << "SUM of numbers: " << sumVal << std::endl;
return 0;
}
写在最后
如果文章内容有任何错误或者您对文章有任何疑问,欢迎私信博主或者在评论区指出 💬💬💬。
如果大家有更优的时间、空间复杂度方法,欢迎评论区交流。
最后,感谢您的阅读,如果感到有所收获的话可以给博主点一个 👍 哦。