Map Sum Pairs

本文介绍了一种使用Trie数据结构优化前缀搜索的方法,通过实例展示如何在MapSumPairs问题中实现高效查找。文章详细解释了Trie节点的构造及插入、更新和查询操作,展示了该方法在速度和内存使用上的优势。

things like prefix should use Trie. I draw a picture to display this solution.

root
a
b
c
...
sub_a1
sub_b1
sub_c1
sub_a2
sub_b2
sub_c2
sub_c...
/**
Runtime: 12 ms, faster than 56.55% of Java online submissions for Map Sum Pairs.

Memory Usage: 40 MB, less than 14.29% of Java online submissions for Map Sum Pairs.
*/
class MapSum {

    // for update count when insert an existed key
    HashMap<String, Integer> map;
    TrieNode root;
    
    /** Initialize your data structure here. */
    public MapSum() {
        map = new HashMap<>();
        root = new TrieNode();
    }
    
    public void insert(String key, int val) {
        if (key == null) {
             return;
        }
        // for update an existed key
        int delta = val - map.getOrDefault(key, 0);
        map.put(key, val);
        TrieNode cur = root;
        cur.count += delta;
        for (char c : key.toCharArray()) {
            cur.children.putIfAbsent(c, new TrieNode());
            cur = cur.children.get(c);
            cur.count += delta;
        }
    }
    
    public int sum(String prefix) {
        if (prefix == null) {
              return 0;
        }
        TrieNode cur = root;
        for (char c : prefix.toCharArray()) {
            cur = cur.children.get(c);
            if (cur == null) {
                return 0;
            }
        }
        return cur.count;
    }
}
class TrieNode {
    HashMap<Character, TrieNode> children = new HashMap<>();
    int count;
}

/**
 * Your MapSum object will be instantiated and called as such:
 * MapSum obj = new MapSum();
 * obj.insert(key,val);
 * int param_2 = obj.sum(prefix);
 */
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值