{"id":331,"date":"2017-09-18T00:23:25","date_gmt":"2017-09-18T07:23:25","guid":{"rendered":"http:\/\/zxi.mytechroad.com\/blog\/?p=331"},"modified":"2018-07-10T18:43:39","modified_gmt":"2018-07-11T01:43:39","slug":"leetcode-677-map-sum-pairs","status":"publish","type":"post","link":"https:\/\/zxi.mytechroad.com\/blog\/tree\/leetcode-677-map-sum-pairs\/","title":{"rendered":"\u82b1\u82b1\u9171 LeetCode 677. Map Sum Pairs"},"content":{"rendered":"<p><iframe loading=\"lazy\" title=\"\u82b1\u82b1\u9171 LeetCode 677. Map Sum Pairs - \u5237\u9898\u627e\u5de5\u4f5c EP61\" width=\"500\" height=\"375\" src=\"https:\/\/www.youtube.com\/embed\/FYluJaicnlY?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe><\/p>\n<p><a href=\"https:\/\/leetcode.com\/problems\/map-sum-pairs\/description\/\">https:\/\/leetcode.com\/problems\/map-sum-pairs\/description\/<\/a><\/p>\n<p><strong>Problem:<\/strong><\/p>\n<p>Implement a MapSum class with\u00a0<code>insert<\/code>, and\u00a0<code>sum<\/code>\u00a0methods.<\/p>\n<p>For the method\u00a0<code>insert<\/code>, you&#8217;ll be given a pair of (string, integer). The string represents the key and the integer represents the value. If the key already existed, then the original key-value pair will be overridden to the new one.<\/p>\n<p>For the method\u00a0<code>sum<\/code>, you&#8217;ll be given a string representing the prefix, and you need to return the sum of all the pairs&#8217; value whose key starts with the prefix.<\/p>\n<p><b>Example 1:<\/b><\/p>\n<pre class=\"\">Input: insert(\"apple\", 3), Output: Null\r\nInput: sum(\"ap\"), Output: 3\r\nInput: insert(\"app\", 2), Output: Null\r\nInput: sum(\"ap\"), Output: 5<\/pre>\n<p><strong>Idea:<\/strong><\/p>\n<p>Prefix tree<\/p>\n<p><a href=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/677-ep61-1.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-336\" src=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/677-ep61-1.png\" alt=\"\" width=\"960\" height=\"540\" srcset=\"https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/677-ep61-1.png 960w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/677-ep61-1-300x169.png 300w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/677-ep61-1-768x432.png 768w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/677-ep61-1-624x351.png 624w\" sizes=\"auto, (max-width: 960px) 100vw, 960px\" \/><\/a><a href=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/677-ep61-2.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-335\" src=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/677-ep61-2.png\" alt=\"\" width=\"960\" height=\"540\" srcset=\"https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/677-ep61-2.png 960w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/677-ep61-2-300x169.png 300w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/677-ep61-2-768x432.png 768w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/677-ep61-2-624x351.png 624w\" sizes=\"auto, (max-width: 960px) 100vw, 960px\" \/><\/a><a href=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/677-ep61-3.png\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-334\" src=\"http:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/677-ep61-3.png\" alt=\"\" width=\"960\" height=\"540\" srcset=\"https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/677-ep61-3.png 960w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/677-ep61-3-300x169.png 300w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/677-ep61-3-768x432.png 768w, https:\/\/zxi.mytechroad.com\/blog\/wp-content\/uploads\/2017\/09\/677-ep61-3-624x351.png 624w\" sizes=\"auto, (max-width: 960px) 100vw, 960px\" \/><\/a><\/p>\n<p><script async src=\"\/\/pagead2.googlesyndication.com\/pagead\/js\/adsbygoogle.js\"><\/script><br \/>\n<ins class=\"adsbygoogle\" style=\"display: block; text-align: center;\" data-ad-layout=\"in-article\" data-ad-format=\"fluid\" data-ad-client=\"ca-pub-2404451723245401\" data-ad-slot=\"7983117522\"><\/ins><br \/>\n<script>\n     (adsbygoogle = window.adsbygoogle || []).push({});\n<\/script><\/p>\n<p><strong>Solution 1<\/strong><\/p>\n<pre class=\"lang:default decode:true\">\/\/ Author: Huahua\r\n\/\/ Running time: 3 ms\r\nclass MapSum {\r\npublic:\r\n    \/** Initialize your data structure here. *\/\r\n    MapSum() {}\r\n    \r\n    void insert(const string&amp; key, int val) {\r\n        int inc = val;\r\n        if (vals_.count(key)) {\r\n            inc -= vals_[key];\r\n        }\r\n        vals_[key] = val;\r\n        for (int i = 1; i &lt;= key.length(); ++i)\r\n            sums_[key.substr(0,i)] += inc;\r\n    }\r\n    \r\n    int sum(const string&amp; prefix) {\r\n        return sums_[prefix];\r\n    }\r\nprivate:\r\n    unordered_map&lt;string, int&gt; vals_;\r\n    unordered_map&lt;string, int&gt; sums_;    \r\n};<\/pre>\n<p><strong>Solution 2:<\/strong><\/p>\n<pre class=\"lang:default decode:true \">class MapSum {\r\npublic:\r\n    \/** Initialize your data structure here. *\/\r\n    MapSum() {}\r\n    \r\n    void insert(string key, int val) {\r\n        int inc = val - vals_[key];\r\n        Trie* p = &amp;root;\r\n        for (const char c : key) {\r\n            if (!p-&gt;children[c])\r\n                p-&gt;children[c] = new Trie();\r\n            p-&gt;children[c]-&gt;sum += inc;\r\n            p = p-&gt;children[c];\r\n        }\r\n        vals_[key] = val;\r\n    }\r\n    \r\n    int sum(string prefix) {\r\n        Trie* p = &amp;root;\r\n        for (const char c : prefix) {\r\n            if (!p-&gt;children[c]) return 0;\r\n            p = p-&gt;children[c];\r\n        }        \r\n        return p-&gt;sum;\r\n    }\r\nprivate:\r\n    struct Trie {\r\n        Trie():children(128, nullptr), sum(0){}\r\n        ~Trie() {\r\n            for (auto child : children)\r\n                if (child) delete child;\r\n            children.clear();\r\n        }\r\n        vector&lt;Trie*&gt; children;\r\n        int sum;        \r\n    };\r\n    \r\n    Trie root; \/\/ dummy root\r\n    unordered_map&lt;string, int&gt; vals_; \/\/ key -&gt; val\r\n};<\/pre>\n<p>with std::unique_ptr<\/p>\n<pre class=\"lang:c++ decode:true \">\/\/ Author: Huahua\r\n\/\/ Running time: 5 ms\r\nclass MapSum {\r\npublic:\r\n    \/** Initialize your data structure here. *\/\r\n    MapSum(): root_(new Trie()) {}\r\n  \r\n    void insert(string key, int val) {      \r\n      int inc = val - vals_[key];\r\n      Trie* p = root_.get();\r\n      for (const char c : key) {\r\n        if (!p-&gt;children[c])\r\n          p-&gt;children[c] = new Trie();\r\n        p-&gt;children[c]-&gt;sum += inc;\r\n        p = p-&gt;children[c];\r\n      }\r\n      vals_[key] = val;\r\n    }\r\n    \r\n    int sum(string prefix) {\r\n      Trie* p = root_.get();\r\n      for (const char c : prefix) {\r\n        if (!p-&gt;children[c]) return 0;\r\n        p = p-&gt;children[c];\r\n      }\r\n\r\n      return p-&gt;sum;        \r\n    }\r\nprivate:\r\n    struct Trie {\r\n        Trie():children(128, nullptr), sum(0){}\r\n        ~Trie() {\r\n          for (auto child : children)\r\n            if (child) {\r\n              delete child;\r\n              child = nullptr;\r\n            }\r\n          children.clear();\r\n        }\r\n        vector&lt;Trie*&gt; children;\r\n        int sum;        \r\n    };\r\n    \r\n    std::unique_ptr&lt;Trie&gt; root_;\r\n    unordered_map&lt;string, int&gt; vals_; \/\/ key -&gt; val\r\n};<\/pre>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>https:\/\/leetcode.com\/problems\/map-sum-pairs\/description\/ Problem: Implement a MapSum class with\u00a0insert, and\u00a0sum\u00a0methods. For the method\u00a0insert, you&#8217;ll be given a pair of (string, integer). The string represents the key and&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[89,45],"tags":[82,177,97,62,96],"class_list":["post-331","post","type-post","status-publish","format-standard","hentry","category-data-structure","category-tree","tag-hashtable","tag-medium","tag-prefix","tag-sum","tag-trie","entry","simple"],"_links":{"self":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/331","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/comments?post=331"}],"version-history":[{"count":9,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/331\/revisions"}],"predecessor-version":[{"id":3069,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/331\/revisions\/3069"}],"wp:attachment":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/media?parent=331"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/categories?post=331"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/tags?post=331"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}