[LeetCode] Map Sum Pairs 映射配对之和

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

这道题让我们实现一个MapSum类,里面有两个方法,insert和sum,其中inser就是插入一个键值对,而sum方法比较特别,是在找一个前缀,需要将所有有此前缀的单词的值累加起来返回。看到这种玩前缀的题,照理来说是要用前缀树来做的。但是博主一般想偷懒,不想新写一个结构或类,于是就使用map来代替前缀树啦。博主开始想到的方法是建立前缀和一个pair之间的映射,这里的pair的第一个值表示该词的值,第二个值表示将该词作为前缀的所有词的累加值,那么我们的sum函数就异常的简单了,直接将pair中的两个值相加即可。关键就是要在insert中把数据结构建好,构建的方法也不难,首先我们suppose原本这个key是有值的,我们更新的时候只需要加上它的差值即可,就算key不存在默认就是0,算差值也没问题。然后我们将first值更新为val,然后就是遍历其所有的前缀了,给每个前缀的second都加上diff即可,参见代码如下:

解法一:

class MapSum {

public:
    /** Initialize your data structure here. */
    MapSum() {}

    void insert(string key, int val) {
        int diff = val - m[key].first, n = key.size();
        m[key].first = val;
        for (int i = n - 1; i > 0; --i) {
            m[key.substr(0, i)].second += diff;
        }
    }

    int sum(string prefix) {
        return m[prefix].first + m[prefix].second;
    }

private:
    unordered_map<string, pair<int, int>> m;
};

下面这种方法是论坛上投票最高的方法,感觉很叼,用的是带排序的map,insert就是把单词加入map。在map里会按照字母顺序自动排序,然后在sum函数里,我们根据prefix来用二分查找快速定位到第一个不小于prefix的位置,然后向后遍历,向后遍历的都是以prefix为前缀的单词,如果我们发现某个单词不是以prefix为前缀了,直接break;否则就累加其val值,参见代码如下: 

解法二:

class MapSum {

public:
    /** Initialize your data structure here. */
    MapSum() {}

    void insert(string key, int val) {
        m[key] = val;
    }

    int sum(string prefix) {
        int res = 0, n = prefix.size();
        for (auto it = m.lower_bound(prefix); it != m.end(); ++it) {
            if (it->first.substr(0, n) != prefix) break;
            res += it->second;
        }
        return res;
    }

private:
    map<string, int> m;
}; 

参考资料:

https://discuss.leetcode.com/topic/103924/java-map-solution

https://discuss.leetcode.com/topic/104006/c-easy-solution-ordered-map

本文转自博客园Grandyang的博客,原文链接:[LeetCode] Map Sum Pairs 映射配对之和

,如需转载请自行联系原博主。

时间: 2024-08-04 14:38:07

[LeetCode] Map Sum Pairs 映射配对之和的相关文章

[LeetCode] Two Sum IV - Input is a BST 两数之和之四 - 输入是二叉搜索树

Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target. Example 1: Input: 5 / \ 3 6 / \ \ 2 4 7 Target = 9 Output: True Example 2: Input: 5 / \ 3 6 / \ \ 2 4

[LeetCode] Path Sum IV 二叉树的路径和之四

If the depth of a tree is smaller than 5, then this tree can be represented by a list of three-digits integers. For each integer in this list: The hundreds digit represents the depth D of this node, 1 <= D <= 4. The tens digit represents the positio

[LeetCode] K Inverse Pairs Array K个翻转对数组

Given two integers n and k, find how many different arrays consist of numbers from 1 to n such that there are exactly k inverse pairs. We define an inverse pair as following: For ith and jth element in the array, if i < j and a[i] > a[j] then it's a

Dozer对象映射框架Map到JSONString映射问题排查

引言 Dozer是一个优秀的对象映射的框架,可以帮助程序员减少大量的对象之间映射的get/set代码,在ATA上有好几篇文章介绍了dozer的使用:dozer开发手册使用Dozer帮你提高开发效率(解决繁琐的DO转BO.TO转BO问题) 有兴趣的同学,可以去看下基本的使用. 问题 我在开发后台系统中,经常会遇到从前台提交的对象,转为后台的服务模型对象做操作,通过dozer工具,灵活的配置就可以轻易的解决.我需要将将一个对象的Map对象转为json的字符串,按照dozer的文档需要编写自定义的Co

[LeetCode]129.Sum Root to Leaf Numbers

[题目] Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. An example is the root-to-leaf path 1->2->3 which represents the number 123. Find the total sum of all root-to-leaf numbers. For example, 1 /

[LeetCode]--371. Sum of Two Integers

Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. Example: Given a = 1 and b = 2, return 3. Credits: Special thanks to @fujiaozhu for adding this problem and creating all test cases. 不用+号肯定想到用Java位运算 位运算中

[LeetCode]--404. Sum of Left Leaves

Find the sum of all left leaves in a given binary tree. Example: 3 / \ 9 20 / \ 15 7 There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24. 我们递归dfs的时候,是求解的全部子树,但是如果我们弄个标志位,判断是不是左子树,那么那个递归一样可以用. public int sumOfLef

[LeetCode] Range Sum Query - Immutable

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. Example: Given nums = [-2, 0, 3, -5, 2, -1] sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -> -3 Note: You may assume that the array do

[LeetCode] Two Sum

Given an array of integers, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that