您的位置:首页 > 其它

432. All O`one Data Structure

2016-10-31 21:08 387 查看
public class AllOne {

/** Initialize your data structure here. */
public AllOne() {

}
int Inc = 0;
HashMap<Integer,Set<String>> hm =  new HashMap<>();//key是字符串的次数,set放这个数量的字符串
HashMap<String ,Integer> hashMap = new HashMap<>();//key是字符串,value是这个字符串有的数量
Set<Integer> numSet = new TreeSet<Integer>();

/** Inserts a new key <Key> with value 1. Or increments an existing key by 1. */
public void inc(String key) {
Inc++;
if(hashMap.containsKey(key)){
hm.get(hashMap.get(key)).remove(key);//这个数量下的se必须去掉这个字符串,因为字符串数量加了1,
hashMap.put(key,hashMap.get(key)+1);//这个字符串的数量加一
if (hm.containsKey(hashMap.get(key))) {
hm.get(hashMap.get(key)).add(key);//把字符串放到改变后的数量的set中,不过这种情况下一个数量的set必须已经创建
}else {
Set<String > set = new HashSet<>();//这个事set没创建,必须创建
set.add(key);
hm.put(hashMap.get(key),set);
}
}else {
hashMap.put(key,1);
if (!hm.containsKey(1)) {
Set<String> set = new HashSet<String>();
set.add(key);
hm.put(1, set);
}else {
hm.get(1).add(key);
}
}
}

/** Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. */
public void dec(String key) {//这个和inc函数一样
if (hashMap.containsKey(key)){
if (hashMap.get(key)==1){
hm.get(1).remove(key);
hashMap.remove(key);
}
else {

hm.get(hashMap.get(key)).remove(key);
hashMap.put(key,hashMap.get(key)-1);
hm.get(hashMap.get(key)).add(key);

}
}
}

/** Returns one of the keys with maximal value. */
public String getMaxKey() {//Inc是常熟,所以这也是o(1),Inc是改进,意味着数量最多的单词不超过inc的总次数

for (int i=Inc;i>=0;i--)//for(int i=10000;i>=0;i--)这意味着数量最多的单词不超过10000
if (hm.containsKey(i)){
for(Object s:hm.get(i).toArray()){
return String.valueOf(s);
}
}
return "";
}

/** Returns one of the keys with Minimal value. */
public String getMinKey() {

for (int i=1;i<=Inc;i++)
if (hm.containsKey(i)){
for(Object s:hm.get(i).toArray()){
return String.valueOf(s);
}
}
return "";
}
}

/**
* Your AllOne object will be instantiated and called as such:
* AllOne obj = new AllOne();
* obj.inc(key);
* obj.dec(key);
* String param_3 = obj.getMaxKey();
* String param_4 = obj.getMinKey();
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  结构 hashmap class