码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 677. Map Sum Pairs

时间:2019-12-28 21:19:14      阅读:70      评论:0      收藏:0      [点我收藏+]

标签:key   send   next   etc   log   prototype   pair   func   har   

使用前缀树

 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;
    }

leetcode 677. Map Sum Pairs

标签:key   send   next   etc   log   prototype   pair   func   har   

原文地址:https://www.cnblogs.com/rubylouvre/p/12112893.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!