原题链接在这里:https://leetcode.com/problems/maximum-frequency-stack/
题目:
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.
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
2 * 104
calls will be made to push
and pop
.pop
.题解:
In order to popped the most frequent element and if ther are tie case pop the recent one.
We could have a Map<Integer, Stack<Integer>> group which records the frequency to the stack.
If x are pushed 3 times, then in group(1,2,3), each of them, the stack contains x.
Time Complexity: push, O(1). pop, O(1).
Space: O(n). n is the number of elements in group.
AC Java:
1 class FreqStack { 2 Map<Integer, Integer> freq; 3 Map<Integer, Stack<Integer>> group; 4 int max; 5 6 public FreqStack() { 7 freq = new HashMap<>(); 8 group = new HashMap<>(); 9 max = 0; 10 } 11 12 public void push(int val) { 13 int f = freq.getOrDefault(val, 0) + 1; 14 freq.put(val, f); 15 group.computeIfAbsent(f, z -> new Stack<Integer>()).push(val); 16 max = Math.max(max, f); 17 } 18 19 public int pop() { 20 int res = group.get(max).pop(); 21 freq.put(res, max - 1); 22 if(group.get(max).isEmpty()){ 23 group.remove(max); 24 max--; 25 } 26 27 return res; 28 } 29 } 30 31 /** 32 * Your FreqStack object will be instantiated and called as such: 33 * FreqStack obj = new FreqStack(); 34 * obj.push(val); 35 * int param_2 = obj.pop(); 36 */