ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

leetcode-895 Maximum Frequency Stack

2020-11-06 11:01:17  阅读:256  来源: 互联网

标签:fre self pop leetcode Frequency push stack dic 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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有