首页 > 其他分享 >LWC 50:677. Map Sum Pairs

LWC 50:677. Map Sum Pairs

时间:2023-07-10 16:32:16浏览次数:53  
标签:Map Pairs cur val mem Sum int key root


LWC 50:677. Map Sum Pairs

传送门:677. Map Sum Pairs

Problem:

Implement a MapSum class with insert, and sum methods.

For the method insert, you’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.

For the method sum, you’ll be given a string representing the prefix, and you need to return the sum of all the pairs’ value whose key starts with the prefix.

Example 1:

Input: insert(“apple”, 3), Output: Null
Input: sum(“ap”), Output: 3
Input: insert(“app”, 2), Output: Null
Input: sum(“ap”), Output: 5

两种做法,在插入时,记入所有前缀,查询快。第二种做法为插入时直接记录,查询时计算所有前缀, 插入快。

插入O(n)查询O(1)

class MapSum {

    /** Initialize your data structure here. */
    Map<String, Integer> mem;
    Map<String, Integer> set;
    public MapSum() {
        mem = new HashMap<>();
        set = new HashMap<>();
    }

    public void insert(String key, int val) {
        if (!set.containsKey(key)){
            set.put(key, val);
            for (int i = 0; i <= key.length(); ++i){
                String sub = key.substring(0, i);
                mem.put(sub,mem.getOrDefault(sub, 0) + val);
            }            
        }else{
            int cnt = set.get(key);
            for (int i = 0; i <= key.length(); ++i){
                String sub = key.substring(0, i);
                mem.put(sub, mem.get(sub) - cnt + val);
            }
        }
    }

    public int sum(String prefix) {
        if (!mem.containsKey(prefix)) return 0;
        return mem.get(prefix);
    }
}

插入O(1)查询O(n)

class MapSum {
    /** Initialize your data structure here. */
    Map<String, Integer> mem;

    public MapSum() {
        mem = new HashMap<>();
    }

    public void insert(String key, int val) {
        mem.put(key, val);
    }

    public int sum(String prefix) {
        int sum = 0;
        for (String pre : mem.keySet()) {
            for (int i = 0; i <= pre.length(); ++i) {
                if (prefix.equals(pre.substring(0, i))) {
                    sum += mem.get(pre);
                }
            }
        }
        return sum;
    }
}

当然你还可以使用Trie来维护前缀,代码如下:

class MapSum {

    class TrieNode{
        TrieNode[] children = new TrieNode[26];
        int val;
    }

    TrieNode build(TrieNode root, String key, int val) {
        char[] cs = key.toCharArray();
        if (root == null) root = new TrieNode();
        TrieNode cur = root;
        cur.val = val;
        for (char c : cs) {
            if (cur.children[c - 'a'] == null) cur.children[c - 'a'] = new TrieNode();
            cur = cur.children[c - 'a'];
            cur.val += val;
        }
        return root;
    }

    int search(TrieNode root, String prefix) {
        TrieNode cur = root;
        for (char c : prefix.toCharArray()) {
            if (cur.children[c - 'a'] != null) cur = cur.children[c - 'a'];
            else return 0;
        }
        return cur.val;
    }

    Map<String, Integer> mem;
    TrieNode root;
    public MapSum() {
        mem = new HashMap<>();
        root = null;
    }

    public void insert(String key, int val) {
        if (!mem.containsKey(key)) {
            root = build(root, key, val);
            mem.put(key, val);
        }
        else {
            int sub = mem.get(key);
            root = build(root, key, val - sub);
            mem.put(key, val);
        }
    }

    public int sum(String prefix) {
        return search(root, prefix);
    }
}


标签:Map,Pairs,cur,val,mem,Sum,int,key,root
From: https://blog.51cto.com/u_16184402/6678329

相关文章

  • globalmapper加载DOM显示无法确定投影和datum
    Theprojection/datumofthisGeoTIFFfilecouldnotbedeterminedautomatically.Pleaseconfirmtheprojection/datumforthisfile.Checkwithyourdatasupplierforthisinformationifyoudonothaveit.选择loadfromfile,选择arcgis导出的某个矢量文件的.prj文......
  • mapbox_master
    1.项目描述根据奔跑吧面条的**vue-big-screen**开源框架基础上进行修改。项目需要全屏展示(按F11)。项目部分区域使用了全局注册方式,增加了打包体积,在实际运用中请使用按需引入。项目环境:Vue-cli、DataV、Echarts、Webpack、Npm、Node,axios,mock。请拉取master分支的代码,其......
  • HashMap 源码阅读
    HashMap源码阅读HashMap是线程不安全的,若需要考虑线程安全则需要用HashTable属性//默认大小1<<4为16staticfinalintDEFAULT_INITIAL_CAPACITY=1<<4;//最大2的30次方staticfinalintMAXIMUM_CAPACITY=1<<30;//默认负载因子0.75staticfinal......
  • Mapbox、GeoServer离线部署矢量地图
    Mapbox、GeoServer离线部署矢量地图关键词:Mapbox、GeoServer、Tomcat、PostgreSQL、PostGis一、地图数据获取使用OpenStreetMap获取中国的矢量地图数据二、安装GeoServer及VectorTiles扩展将下载好的GeoServer.war放入Tomcat,启动Tomcat后将VectorTiles扩展中的四个jar包放入GeoSe......
  • bitmap
    bitmap使用情景用户签到,打卡,电影广告是否被点击过docker进入redisdockerexec-it<container_name>redis-cli常用指令setbit键值offset(从0开始)0|1getbit键值offsetstrlen键值(统计的是字节数占用多少:例如我们只SETBITa101和SETBITa111,strlena1......
  • 内置高阶函数map
    说明map函数可以对一个可迭代对象的每个元素进行处理,处理的方式通过指定的函数决定。并返回处理结果(迭代器对象)示例'''map()函数是Python内置的高阶函数之一,它接受一个函数和一个可迭代对象作为参数,将函数应用于可迭代对象中的每个元素,并返回一个新的迭代器对象其语法:map(func......
  • Ibatis的resultMap的cacheModel研究
    1、Ibatis的resultMap的cacheModel研究http://lggege.iteye.com/blog/216615  2、缓存cacheModelhttp://imticg.iteye.com/blog/216809......
  • CF1817E Half-sum
    greedy把数分成两个集合\(A,B\),且\(A<B\)。令每个集合的数的个数分别是\(a,b\)。令\(A_1\dotsA_a,B_1\dotsB_b\)分别有序。定理\(1\)\(A\)集合合并的顺序一定是从大往小的,\(B\)集合是从小往大的。应该很好猜到,但是证明需要一点推导。大概可以局部到\(x,y,z,w\)......
  • SteamAPI_Init 返回失败的原因
    SteamAPI_Init您在自己的项目内设置SteamworksAPI后,就可以通过调用 SteamAPI_Init 函数,初始化此API并开始使用。这样即可设置全局状态,并填入可以通过与此接口名称匹配的全局函数访问的接口指针。 必须调用此函数并返回成功,才能访问任何 Steamworks接口!如果Steamworks......
  • HashMap的实现原理详解(看这篇就够了)
    一线资深java工程师明确了需要精通集合容器,尤其是今天我谈到的HashMap。HashMap在Java集合的重要性不亚于Volatile在并发编程的重要性(可见性与有序性)。我会重点讲解以下9点:1.HashMap的数据结构2.HashMap核心成员3.HashMapd的Node数组4.HashMap的数据存储5.HashMap的哈希函数6.哈......