zoukankan      html  css  js  c++  java
  • 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;
        }
    
  • 相关阅读:
    cfdem链接库地址不对的解决方法(liblmp_auto.so)
    总结入门学习OpenFOAM的资料(网址、论坛、帖子、博客等)
    运行cfdemCFDEMuti编译时出现的错误
    mapreduce 的三种测试方式
    Shell 编程
    hadoop集群搭建
    hadoop的环境配置
    hadoop 模板虚拟机环境准备以及对模板机的克隆
    linux总结
    解决maven控制台出现乱码情况
  • 原文地址:https://www.cnblogs.com/rubylouvre/p/12112893.html
Copyright © 2011-2022 走看看