【python3】leetcode 895. Maximum Frequency Stack(Hard)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/maotianyi941005/article/details/85220643

895. Maximum Frequency Stack(Hard)

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.

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:
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].

参考了这道题的solution,没我想的简单——》solution 

注意:

1 当栈为空时的pop 不return:先判断

2 用maxfreq记录当下数量最多的字符数量,pop后使用maxfreq-- , 刚开始有点想不通觉得maxfreq不连续,自己测试了一下,发现程序跑的通,过程如下

  比如一个字符串“ssssa”,s的个数是4,a的个数是1 ——》maxfreq = 4

pop:s,maxfreq = 3

pop:s,maxfreq = 2

pop:s,maxfreq = 1

pop:a,maxfreq = 1 pop from top

pop:s,maxfreq = 0

所以maxfreq一定是连续的。

class FreqStack:

    def __init__(self):
        self.freq = collections.Counter()
        self.list = collections.defaultdict(list)
        self.maxfreq = 0

    def push(self, x):
        """
        :type x: int
        :rtype: void
        """
        f = self.freq[x] + 1
        self.freq[x] = f
        if f > self.maxfreq:self.maxfreq = f
        self.list[f].append(x)
        
        

    def pop(self):
        """
        :rtype: int
        """ 
        if self.maxfreq != 0:# if none donnot return 
            x = self.list[self.maxfreq].pop()#pop from stack top
            self.freq[x] -= 1
            if not self.list[self.maxfreq]:# not none or []->update maxfreq
                self.maxfreq -= 1     
            return x

# Your FreqStack object will be instantiated and called as such:
# obj = FreqStack()
# obj.push(x)
# param_2 = obj.pop()

猜你喜欢

转载自blog.csdn.net/maotianyi941005/article/details/85220643
今日推荐