博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
677. Map Sum Pairs
阅读量:5065 次
发布时间:2019-06-12

本文共 2598 字,大约阅读时间需要 8 分钟。

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

 

class MapSum {    map
mp;public: /** Initialize your data structure here. */ MapSum() {} void insert(string key, int val) { mp[key]=val; } int sum(string prefix) { /* if (mp.find(prefix)==mp.end()){ return 0; } */ int res=0, n=prefix.size(); for(auto iter=mp.lower_bound(prefix);iter!=mp.end();++iter) { if(iter->first.substr(0,n)!=prefix) break; res+=iter->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); */

c++ map lower_bound upper_bound用法

运行 https://www.cnblogs.com/billin/archive/2011/09/01/2162102.html 一下代码就知道了

#include#include
int main(){ using namespace std; map
m1; map
::const_iterator m1_AcIter,m1_RcIter; typedef pair
Int_Pair; m1.insert(Int_Pair(1,10)); m1.insert(Int_Pair(2,20)); m1.insert(Int_Pair(3,30)); m1_RcIter=m1.lower_bound(2); cout<<"The first elem of map m1 with a key greater than 2 is: " <
second<<"."<
second<<"."<
first); cout<<"The element of m1 with a key mathing the last element is: " <
second<<"."<

输出

python代码

class MapSum(object):    def __init__(self):        """        Initialize your data structure here.        """        self.d={}            def insert(self, key, val):        """        :type key: str        :type val: int        :rtype: void        """        self.d[key]=val            def sum(self, prefix):        """        :type prefix: str        :rtype: int        """        return sum(self.d[i] for i in self.d if i.startswith(prefix))         # Your MapSum object will be instantiated and called as such:# obj = MapSum()# obj.insert(key,val)# param_2 = obj.sum(prefix)

 

转载于:https://www.cnblogs.com/learning-c/p/9271525.html

你可能感兴趣的文章
设置虚拟机虚拟机中fedora上网配置-bridge连接方式(图解)
查看>>
[置顶] Android仿人人客户端(v5.7.1)——人人授权访问界面
查看>>
Eclipse 调试的时候Tomcat报错启动不了
查看>>
ES6内置方法find 和 filter的区别在哪
查看>>
Android实现 ScrollView + ListView无滚动条滚动
查看>>
java学习笔记之String类
查看>>
UVA 11082 Matrix Decompressing 矩阵解压(最大流,经典)
查看>>
jdk从1.8降到jdk1.7失败
查看>>
硬件笔记之Thinkpad T470P更换2K屏幕
查看>>
iOS开发——缩放图片
查看>>
HTTP之URL的快捷方式
查看>>
满世界都是图论
查看>>
配置链路聚合中极小错误——失之毫厘谬以千里
查看>>
代码整洁
查看>>
蓝桥杯-分小组-java
查看>>
Android Toast
查看>>
iOS开发UI篇—Quartz2D使用(绘制基本图形)
查看>>
docker固定IP地址重启不变
查看>>
桌面图标修复||桌面图标不正常
查看>>
JavaScript基础(四)关于对象及JSON
查看>>