哈希表
May 14, 2024Less than 1 minute
1. 两数之和 - 力扣(LeetCode)
这题是很多题的母题, 对于 hash 表的应用一定要熟练
49. 字母异位词分组 - 力扣(LeetCode)
题目描述:
输入: strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
输出: ["bat"],["nat","tan"],["ate","eat","tea"]("bat"],["nat","tan"],["ate","eat","tea")
- 方法一:用哈希表,对每个词的各个字母出现的次数做一个唯一 key, 然后匹配到哈希表里。
- 方法二:
- 方法三:
注意:let stringKey = bitArray.join(",");
这里 join 的时候一定要分割,不然[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,10]
和[0,10,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]
,它们都会产生相同的字符串键0000000000000000000010
。
function groupAnagrams(strs: string[]): string[][] {
let dir = {};
for (let i = 0; i < strs.length; i++) {
let bitArray = Array.from({ length: 26 }, () => 0);
for (let j = 0; j < strs[i].length; j++) {
bitArray[strs[i][j].charCodeAt(0) - "a".charCodeAt(0)] += 1;
}
let stringKey = bitArray.join(",");
if (stringKey in dir) {
dir[stringKey].push(strs[i]);
} else {
dir[stringKey] = [strs[i]];
}
}
let returnList = [];
for (let item in dir) {
returnList.push(dir[item]);
}
return returnList;
}
怎么作出好看的 哈希表呢