Ruby's Louvre

每天学习一点点算法

导航

leetcode 677. Map Sum Pairs

使用前缀树

 function Node() {
      this.value = 0
      this.children = {}
    }
    class MapSum {
      constructor() {
        this.root = new Node()
      }
      insert(word, val) {
        var node = this.root;
        for (let next of word) {
          if (!node.children[next]) {
            node.children[next] = new Node()
          }
          node = node.children[next]
          node.value += val
        }
        node.value += val
        node.isEnd = true
      }
      sum(word) {
        var node = this.root;
        for (let next of word) {
          node = node.children[next]
        }
        return node && node.value
      }
    }

    var tire = new MapSum()
    tire.insert("apple", 3)
    console.log(tire.sum("ap"))
    tire.insert("app", 2);
    console.log(tire.sum("ap"))

或者 使用map优化一下

    var MapSum = function () { // Space: O(n)
      this.map = new Map();
      this.root = new TrieNode();
    };

    /** 
     * @param {string} key 
     * @param {number} val
     * @return {void}
     */
    MapSum.prototype.insert = function (key, val) { // Time: O(k), k = leng(key)
      const delta = val - (this.map.get(key) || 0);
      this.map.set(key, val);
      let node = this.root;
      node.score += delta;
      for (const char of key) {
        if (!node.children.has(char)) {
          node.children.set(char, new TrieNode());
        }
        node = node.children.get(char);
        node.score += delta;
      }
    };

    /** 
     * @param {string} prefix
     * @return {number}
     */
    MapSum.prototype.sum = function (prefix) { // Time: O(k), k = len(prefix)
      let node = this.root;
      for (const char of prefix) {
        node = node.children.get(char);
        if (!node) return 0;
      }
      return node.score;
    };

    function TrieNode() {
      this.children = new Map();
      this.score = 0;
    }
机器瞎学/数据掩埋/模式混淆/人工智障/深度遗忘/神经掉线/计算机幻觉/专注单身二十五年

posted on 2019-12-28 20:12  司徒正美  阅读(147)  评论(0编辑  收藏  举报