677_键值映射_2021.11.14
实现一个 MapSum 类,支持两个方法,insert 和 sum:
MapSum() 初始化 MapSum 对象
void insert(String key, int val) 插入 key-val 键值对,字符串表示键 key ,整数表示值 val 。如果键 key 已经存在,那么原来的键值对将被替代成新的键值对。
int sum(string prefix) 返回所有以该前缀 prefix 开头的键 key 的值的总和。
今天的题比较简单,如果用单纯的STL自带的数据结构,利用unordered_map直接记录键值对,然后在输出sum的时候利用find函数遍历unordered_map,pos为0代表找到前缀,累加则找到结果:
1 class MapSum { 2 public: 3 MapSum() { 4 mapKstrVint; 5 } 6 7 void insert(string key, int val) { 8 mapKstrVint[key] = val; 9 } 10 11 int sum(string prefix) { 12 13 int sumNum = 0; 14 15 for (auto it = mapKstrVint.begin(); it != mapKstrVint.end(); it++) { 16 string tmpKey = it->first; 17 18 if (tmpKey.find(prefix) == 0) { 19 sumNum += it->second; 20 } 21 } 22 23 24 return sumNum; 25 } 26 27 public: 28 unordered_map<string, int> mapKstrVint; 29 };
题解——前缀哈希映射,思路是记录所有可能的前缀子串,同步当前传入的value,如果后续存在相同的键不同的value,则会更新所有的前缀所对应的value,如果不存在,则继续同步
class MapSum1{ public: MapSum1() { } public: void insert(string key, int val) { int delta = val; if (map.count(key)) { delta -= map[key]; } map[key] = delta; for (int i = 1; i < key.size(); i++) { prefixmap[key.substr(0, i)] += delta; } } int sum(string prefix) { return prefixmap[prefix]; } private: unordered_map<string, int> map; unordered_map<string, int> prefixmap; };
题解——字典树,思路同前缀哈希映射,只是在这一情况下,记录前缀的数据结构是自己实现的(没看太懂):
// 参考题解(字典树) struct TrieNode { int val; TrieNode * next[26]; TrieNode() { this->val = 0; for (int i = 0; i < 26; ++i) { this->next[i] = nullptr; } } }; class MapSum2 { public: MapSum2() { this->root = new TrieNode(); } void insert(string key, int val) { int delta = val; if (cnt.count(key)) { delta -= cnt[key]; } cnt[key] = val; TrieNode * node = root; for (auto c : key) { if (node->next[c - 'a'] == nullptr) { node->next[c - 'a'] = new TrieNode(); } node = node->next[c - 'a']; node->val += delta; } } int sum(string prefix) { TrieNode * node = root; for (auto c : prefix) { if (node->next[c - 'a'] == nullptr) { return 0; } else { node = node->next[c - 'a']; } } return node->val; } private: TrieNode * root; unordered_map<string, int> cnt; };