力扣打卡:677. 键值映射
解题思路
没什么好的思路,想到用HashMap来解决问题
- 添加时时间复杂度为O(1)
- 求和时,时间复杂度为
O(map.size() * prefix.length())
注意查找时,查找的条件即可
代码
class MapSum {
// 使用HashMap
HashMap<String,Integer> map;
public MapSum() {
this.map = new HashMap<>();
}
public void insert(String key, int val) {
this.map.put(key,val);
}
public int sum(String prefix) {
int sum = 0;
for(Map.Entry<String,Integer> entry : map.entrySet()){
if(entry.getKey().length() >= prefix.length()){
boolean flag = true;
for(int i=0; i<prefix.length(); i++){
if(entry.getKey().charAt(i)!=prefix.charAt(i)){flag=false; break;}
}
if(flag){sum += entry.getValue();}
}
}
return sum;
}
}
/**
* Your MapSum object will be instantiated and called as such:
* MapSum obj = new MapSum();
* obj.insert(key,val);
* int param_2 = obj.sum(prefix);
*/