哈希表-设计键
字母异位词分组
题解:
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
//键值设置为排序之后的字符串
unordered_map<string,vector<string>> hashmap;
//字符串数组的长度
int n = strs.size();
//遍历数组
for(int i = 0;i<n;i++){
string temp = strs[i];
//对字符串排序
sort(temp.begin(),temp.end());
if(hashmap.count(temp)>0){
//存在 加入到对应的键值队伍中
hashmap[temp].push_back(strs[i]);
}else{
//不存在
hashmap[temp] = {strs[i]};
}
}
vector<vector<string>> result;
//遍历哈希映射
for(auto it = hashmap.begin();it!=hashmap.end();it++){
result.push_back((*it).second);
}
return result;
}
};
有效的数独
题解:三个哈希映射来存储行、列、九宫格出现的数字,一次遍历判断所有
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
//初始化数据
unordered_map<int,unordered_set<int>> hashmap_row;
unordered_map<int,unordered_set<int>> hashmap_col;
unordered_map<int,unordered_set<int>> hashmap_box;
//判断棋盘是否有效
for(int i = 0;i<9;i++){
for(int j = 0;j<9;j++){
char temp = board[i][j];
if(temp != '.'){
int n = (int)temp;
//第几个九宫格
int box_index = (i/3)*3+j/3;
//i行
if(hashmap_row[i].count(n)>0){
return false;
}else{
hashmap_row[i].insert(n);
}
//第j列
if(hashmap_col[j].count(n)>0){
return false;
}else{
hashmap_col[j].insert(n);
}
//第box_index个九宫格
if(hashmap_box[box_index].count(n)>0){
return false;
}else{
hashmap_box[box_index].insert(n);
}
}
}
}
return true;
}
};
寻找重复的子树
题解:策略:以二叉树的序列化字符串(结点值之前使用空格隔开)为键,在树中出现的次数为值
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
//将子树序列化
string helper(TreeNode*root, vector<TreeNode*>&result, unordered_map<string,int>&mp) {
string str;
if(root == NULL) {
return "#";
}
//对root进行序列化 结点值之间用空格隔开 使用递归对左子树和右子树序列化
str = to_string(root->val) + ' ' + helper(root->left,result,mp) + ' '+helper(root->right,result,mp);
//序列出现的次数加1
mp[str] +=1;
//第二次出现时该值为2 说明重复 加入结果集中 若后续还有重复 不用再加入
if(mp[str] == 2) {
result.push_back(root);
}
return str;
}
vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
//返回结果的数组
vector<TreeNode*> result;
//哈希映射 二叉树的序列化为键 出现的次数为值
unordered_map<string,int> mp;
//先序遍历子树
helper(root,result,mp);
return result;
}
};