其他分享
首页 > 其他分享> > leetcode-895 Maximum Frequency Stack

leetcode-895 Maximum Frequency Stack

作者:互联网

Implement FreqStack, a class which simulates the operation of a stack-like data structure.

FreqStack has two functions:
   push(int x), which pushes an integer x onto the stack.    pop(), which removes and returns the most frequent element in the stack.     If there is a tie for most frequent element, the element closest to the top of the stack is removed and returned.

输入输出实例:

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:
After making six .push operations, the stack is [5,7,5,7,4,5] from bottom to top.  Then:

pop() -> returns 5, as 5 is the most frequent.
The stack becomes [5,7,5,7,4].

pop() -> returns 7, as 5 and 7 is the most frequent, but 7 is closest to the top.
The stack becomes [5,7,5,4].

pop() -> returns 5.
The stack becomes [5,7,4].

pop() -> returns 4.
The stack becomes [5,7].

这道题我试过几次暴力,发现只要出现循环就会超时TnT ,所以看了一下其他人都说需要多加一个频率栈,就试了一下,发现可行。

 1 class FreqStack:
 2 
 3     def __init__(self):
 4         self.dic = {}
 5         self.fre = {}
 6         self.maxNum = 0
 7 
 8     def push(self, x: int) -> None:
 9         if x in self.dic:
10             self.dic[x] += 1
11         else:
12             self.dic[x] = 1
13         t = self.dic[x]
14         if t in self.fre:
15             if x not in self.fre[t]:
16                 self.fre[t].append(x)
17         else:
18             self.fre[t] = [x]
19         if self.dic[x] > self.maxNum:
20             self.maxNum = self.dic[x]
21         
22 
23     def pop(self) -> int:
24         #temp = sorted(self.dic.items(), key = lambda x:x[1], reverse=True)
25         if len(self.fre[self.maxNum]) == 0:
26             self.maxNum -= 1
27         values = self.fre[self.maxNum].pop()
28         self.dic[values] -= 1
29         return values
30         
31 
32 
33 # Your FreqStack object will be instantiated and called as such:
34 # obj = FreqStack()
35 # obj.push(x)
36 # param_2 = obj.pop()

 

标签:fre,self,pop,leetcode,Frequency,push,stack,dic,Stack
来源: https://www.cnblogs.com/zyq1997/p/13935756.html