Map Sum Pairs
2018-01-14 00:00
459 查看
问题:
Implement a MapSum class with
For the method
For the method
Example 1:
解决:
① 直接用Map实现。
class MapSum { //123ms
Map<String,Integer> map;
/** Initialize your data structure here. */
public MapSum() {
map = new HashMap<>();
}
public void insert(String key, int val) {
map.put(key,val);
}
public int sum(String prefix) {
int res = 0;
for (String key : map.keySet()){
if (key.startsWith(prefix)){
res += map.get(key);
}
}
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);
*/
Implement a MapSum class with
insert, and
summethods.
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
解决:
① 直接用Map实现。
class MapSum { //123ms
Map<String,Integer> map;
/** Initialize your data structure here. */
public MapSum() {
map = new HashMap<>();
}
public void insert(String key, int val) {
map.put(key,val);
}
public int sum(String prefix) {
int res = 0;
for (String key : map.keySet()){
if (key.startsWith(prefix)){
res += map.get(key);
}
}
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);
*/
相关文章推荐
- 677. Map Sum Pairs
- LWC 50:677. Map Sum Pairs
- [LeetCode] Map Sum Pairs 映射配对之和
- 677. Map Sum Pairs
- Map Sum Pairs问题及解法
- 第14周Map Sum Pairs
- leetcode 677. Map Sum Pairs
- 677. Map Sum Pairs
- 【leetcode】Two Sum(unordered_map的使用)
- Incorrect inline parameter map format (missmatched name=value pairs)
- LeetCode 1.Two Sum map 初次使用Markdown*****
- [Leetcode] 1.Two Sum(unordered_map)
- Find K Pairs with Smallest Sum
- 所有整数对之间的位差异数之和(Sum of bit differences among all pairs)
- geeksforgeeks@ Find sum of different corresponding bits for all pairs (Bit manipulation)
- Incorrect inline parameter map format (missmatched name=value pairs): {id},
- poj 1185 炮兵阵地 状态压缩+dp sum dp,s,Map
- Sum of bit differences among all pairs
- 2016.07.13-map的使用(以leetcode1-Two Sum为例)
- uva 1152 4 Values whose Sum is 0 map会超时