Map Sum Pairs

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);
 */
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章