0895.最大频率栈

方法一:哈希表模拟

时间复杂度 $O(1)$,空间复杂度 $O(n \times 2)$。

type FreqStack struct {
	maxFreq     int
	valMapFreq  map[int]int
	freqMapVals map[int][]int
}

func Constructor() FreqStack {
	return FreqStack{valMapFreq: map[int]int{}, freqMapVals: map[int][]int{}}
}

func (this *FreqStack) Push(val int) {
	this.valMapFreq[val]++
	this.freqMapVals[this.valMapFreq[val]] = append(this.freqMapVals[this.valMapFreq[val]], val)
	if this.valMapFreq[val] > this.maxFreq {
		this.maxFreq = this.valMapFreq[val]
	}
}

func (this *FreqStack) Pop() int {
	mlen := len(this.freqMapVals[this.maxFreq])
	res := this.freqMapVals[this.maxFreq][mlen-1]
	this.freqMapVals[this.maxFreq] = this.freqMapVals[this.maxFreq][:mlen-1]
	this.valMapFreq[res]--
	if len(this.freqMapVals[this.maxFreq]) == 0 {
		this.maxFreq--
	}
	return res
}

/**
 * Your FreqStack object will be instantiated and called as such:
 * obj := Constructor();
 * obj.Push(val);
 * param_2 := obj.Pop();
 */