思路:对有序队列里的元素按照频率排序,如果频率相同,根据index比较得到更大的数,表示离栈顶更近。
class FreqStack {
//频率和次序以及val
//根据频率和次序排序,所以需要一个可以排序的集合,想到有序队列
//次序需要频繁的查询,并累加,想到hashmap
int index;
HashMap<Integer,Integer> map;
PriorityQueue<int[]> maxHeap;
public FreqStack() {
index=0;
map=new HashMap<>();
maxHeap=new PriorityQueue<>(new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
if(o1[1]==o2[1]){
return o2[2]-o1[2];
}
return o2[1]-o1[1];
}
});
}
public void push(int val) {
map.put(val,map.getOrDefault(val,0)+1);
maxHeap.add(new int[]{val,map.get(val),index++});
}
public int pop() {
int[] array=maxHeap.poll();
if(array[1]==1){
map.remove(array[0]);
}
else {
map.put(array[0],array[1]-1);
}
return array[0];
}
}