[leetcode] 677. Map Sum Pairs

网友投稿 800 2022-08-23

[leetcode] 677. Map sum Pairs

Description

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: NullInput: sum("ap"), Output: 3Input: insert("app", 2), Output: NullInput: sum("ap"), Output: 5

分析

题目的意思是:实现一个MapSum,有insert,sum方法。

在map里会按照字母顺序自动排序,然后在sum函数里,我们根据prefix来用二分查找快速定位到第一个不小于prefix的位置,然后向后遍历,向后遍历的都是以prefix为前缀的单词,如果我们发现某个单词不是以prefix为前缀了,直接break;否则就累加其val。

代码

class MapSum {private: map m;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; }};/** * Your MapSum object will be instantiated and called as such: * MapSum obj = new MapSum(); * obj.insert(key,val); * int param_2 = obj.sum(prefix); */

参考文献

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

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java 并发学习笔记总结(java语言)
下一篇:30分钟Git命令入门到放弃
相关文章

 发表评论

暂时没有评论,来抢沙发吧~