题目链接:
力扣https://leetcode-cn.com/problems/all-oone-data-structure/
【分析】能力不够,只能用TreeMap来做了,TreeMap的键存元素的出现次数,值为一个Set存出现了这些次的字符串,再用一个HashMap来进行String到出现次数的映射,插入和删除的时候先去查HashMap,再修改TreeMap。
class AllOne {
Map<String, Integer> map = new HashMap<>();
TreeMap<Integer, Set<String>> freq = new TreeMap<>();
public AllOne() {
}
public void show(){
int i;
for(Integer it: freq.keySet()){
System.out.print(it);
System.out.print(" ");
}
System.out.println(" *****");
}
public void inc(String key) {
if(!map.containsKey(key)){
map.put(key, 1);
if(!freq.containsKey(1)){
Set<String> set = new HashSet<>();
set.add(key);
freq.put(1, set);
}else{
freq.get(1).add(key);
}
}else{
int val = map.get(key);
map.put(key, val + 1);
freq.get(val).remove(key);
if(freq.get(val).size() == 0) freq.remove(val);
if(!freq.containsKey(val + 1)){
Set<String> set = new HashSet<>();
set.add(key);
freq.put(val + 1, set);
}else{
freq.get(val + 1).add(key);
}
}
// show();
}
public void dec(String key) {
int val = map.get(key);
if(val == 1){
map.remove(key);
freq.get(val).remove(key);
if(freq.get(val).size() == 0) freq.remove(val);
}else{
map.put(key, map.get(key) - 1);
freq.get(val).remove(key);
if(freq.get(val).size() == 0) freq.remove(val);
if(!freq.containsKey(val - 1)){
HashSet<String> set = new HashSet<>();
set.add(key);
freq.put(val - 1, set);
}else{
freq.get(val - 1).add(key);
}
}
// show();
}
public String getMaxKey() {
if(freq.size() == 0) return "";
Set<String> set = freq.get(freq.lastKey());
return (String)set.toArray()[0];
}
public String getMinKey() {
if(freq.size() == 0) return "";
Set<String> set = freq.get(freq.firstKey());
return (String)set.toArray()[0];
}
}
?
?
|