895. Maximum Frequency Stack

150 阅读1分钟

Design a stack-like data structure to push elements to the stack and pop the most frequent element from the stack.

Implement the FreqStack class:

  • FreqStack() constructs an empty frequency stack.

  • void push(int val) pushes an integer val onto the top of the stack.

  • int pop() removes and returns the most frequent element in the stack.

    • If there is a tie for the most frequent element, the element closest to the stack's top is removed and returned.

 

Example 1:

Input
["FreqStack", "push", "push", "push", "push", "push", "push", "pop", "pop", "pop", "pop"]
[[], [5], [7], [5], [7], [4], [5], [], [], [], []]
Output
[null, null, null, null, null, null, null, 5, 7, 5, 4]

Explanation
FreqStack freqStack = new FreqStack();
freqStack.push(5); // The stack is [5]
freqStack.push(7); // The stack is [5,7]
freqStack.push(5); // The stack is [5,7,5]
freqStack.push(7); // The stack is [5,7,5,7]
freqStack.push(4); // The stack is [5,7,5,7,4]
freqStack.push(5); // The stack is [5,7,5,7,4,5]
freqStack.pop();   // return 5, as 5 is the most frequent. The stack becomes [5,7,5,7,4].
freqStack.pop();   // return 7, as 5 and 7 is the most frequent, but 7 is closest to the top. The stack becomes [5,7,5,4].
freqStack.pop();   // return 5, as 5 is the most frequent. The stack becomes [5,7,4].
freqStack.pop();   // return 4, as 4, 5 and 7 is the most frequent, but 4 is closest to the top. The stack becomes [5,7].

 

Constraints:

  • 0 <= val <= 109
  • At most 2 * 104 calls will be made to push and pop.
  • It is guaranteed that there will be at least one element in the stack before calling pop.

答案

type Stack struct {
	data []int
}

func (s *Stack) Pop() int {
	e := s.data[len(s.data)-1]
	s.data = s.data[:len(s.data)-1]
	return e
}

func (s *Stack) Push(e int) {
	s.data = append(s.data, e)
}

func (s *Stack) Len() int {
	return len(s.data)
}

type FreqStack struct {
	freq map[int]int
	//key为元素的出现频率
	m       map[int]*Stack
	maxFreq int
	maxFunc func(a, b int) int
}

func Constructor() FreqStack {
	return FreqStack{
		freq: make(map[int]int),
		m: make(map[int]*Stack),
		maxFunc: func(a, b int) int {
			if a > b {
				return a
			}
			return b
		},
	}
}

func (this *FreqStack) Push(x int) {
	_, ok := this.freq[x]
    
    this.freq[x]++ 
	this.maxFreq = this.maxFunc(this.maxFreq, this.freq[x])

	_, ok = this.m[this.freq[x]]
	if !ok {
		this.m[this.freq[x]] = &Stack{}
	}
    //相同频率的元素放到同一个栈中,这样在出栈时,即使有多个相同频率的元素
    //也会弹出最接近栈顶的元素(也是最近放进的元素)
	this.m[this.freq[x]].Push(x)
}

func (this *FreqStack) Pop() int {
	x := this.m[this.maxFreq].Pop()
	if this.m[this.freq[x]].Len() == 0 {
		this.maxFreq--
	}

	this.freq[x]--
	return x
}