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 xonto 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:

  1. Input:
  2. ["FreqStack","push","push","push","push","push","push","pop","pop","pop","pop"],
  3. [[],[5],[7],[5],[7],[4],[5],[],[],[],[]]
  4. Output: [null,null,null,null,null,null,null,5,7,5,4]
  5. Explanation:
  6. After making six .push operations, the stack is [5,7,5,7,4,5] from bottom to top. Then:
  7. pop() -> returns 5, as 5 is the most frequent.
  8. The stack becomes [5,7,5,7,4].
  9. pop() -> returns 7, as 5 and 7 is the most frequent, but 7 is closest to the top.
  10. The stack becomes [5,7,5,4].
  11. pop() -> returns 5.
  12. The stack becomes [5,7,4].
  13. pop() -> returns 4.
  14. The stack becomes [5,7].

Note:

  • Calls to FreqStack.push(int x) will be such that 0 <= x <= 10^9.
  • It is guaranteed that FreqStack.pop() won't be called if the stack has zero elements.
  • The total number of FreqStack.push calls will not exceed 10000 in a single test case.
  • The total number of FreqStack.pop calls will not exceed 10000 in a single test case.
  • The total number of FreqStack.push and FreqStack.pop calls will not exceed 150000across all test cases.

这道题让我们实现一种最大频率栈,有入栈和出栈功能,需要每次出栈的都是栈中出现频率最大的数字,若有多个数字的频率相同,那么离栈顶最近的元素先出栈。刚开始看到这道题的时候,博主立马联想到了 [LRU Cache](http://www.cnblogs.com/grandyang/p/4587511.html) 和 [LFU Cache](http://www.cnblogs.com/grandyang/p/6258459.html),想着会不会也需要在迭代器上做文章,但实际是我想多了,虽然同为 Hard 的题目,这道题的解法却要比之前那两道要简单的多。这里只跟数字出现的频率有关,只有在频率相等的情况下才会考虑栈的后入先出的特性,所以一定是需要统计栈中每个数字出现的频率的,我们使用一个 HashMap 来建立每个数字跟其出现次数之间的映射。由于频率相等的数字可能有多个,所以我们必须知道某个特性频率下都有哪些数字,再用一个 HashMap 来建立频率和该频率下所有的数字之间的映射,可以将这些数组放到一个数组或者一个栈中,这里为了简便起见,就使用一个数组了。另外,我们还需要维护一个当前最大频率的变量,可以通过这个值到 HashMap 中快速定位数组的位置。好,一切准备就绪之后就开始解题吧,对于入栈函数 push(),首先需要将x对应的映射值加1,并更新最大频率 mxFreq,然后就是要把x加入当前频率对应的数组中,注意若某个数字出现了3次,那么数字会分别加入频率为 1,2,3 的映射数组中。接下来看出栈函数 pop() 如何实现,由于我们知道当前最大频率 mxFreq,就可以直接去 HashMap 中取出该频率下的所有数字的数组,题目说了若频率相等,取离栈顶最近的元素,这里就是数组末尾的数组,取到之后,要将该数字从数组末尾移除。移除之后,我们要检测一下,若数组此时为空了,说明当前最大频率下之后一个数字,取出之后,最大频率就要自减1,还有不要忘记的就是取出数字的自身的频率值也要自减1,参见代码如下:


解法一:

  1. class FreqStack {
  2. public:
  3. FreqStack() {}
  4. void push(int x) {
  5. mxFreq = max(mxFreq, ++freq[x]);
  6. m[freq[x]].push_back(x);
  7. }
  8. int pop() {
  9. int x = m[mxFreq].back();
  10. m[mxFreq].pop_back();
  11. if (m[freq[x]--].empty()) --mxFreq;
  12. return x;
  13. }
  14. private:
  15. int mxFreq;
  16. unordered_map<int, int> freq;
  17. unordered_map<int, vector<int>> m;
  18. };

我们还可以使用 multimap 来建立频率和数字之间的映射,利用其可重复的特性,那么同一个频率就可以映射多个数字了。同时,由于 multimap 默认是按从小到大排序的,而我们希望按频率从大到小排序,所以加上一个参数使其改变排序方式。在入栈函数中,将x的频率自增1,然后跟x组成 pair 对儿加入 multimap 中。在出栈函数中,由于其是按从大到小排序的,而且后进的排在前面,那么第一个映射对儿就是频率最大且最后加入的数字,将其取出并从 multimap 中移除,并同时将该数字的映射频率值减1即可,参见代码如下:


解法二:

  1. class FreqStack {
  2. public:
  3. FreqStack() {}
  4. void push(int x) {
  5. m.insert({++freq[x], x});
  6. }
  7. int pop() {
  8. int x = m.begin()->second;
  9. m.erase(m.begin());
  10. --freq[x];
  11. return x;
  12. }
  13. private:
  14. unordered_map<int, int> freq;
  15. multimap<int, int, greater_equal<int>> m;
  16. };

Github 同步地址:

https://github.com/grandyang/leetcode/issues/895

参考资料:

https://leetcode.com/problems/maximum-frequency-stack/

https://leetcode.com/problems/maximum-frequency-stack/discuss/163410/C%2B%2BJavaPython-O(1)

https://leetcode.com/problems/maximum-frequency-stack/discuss/229638/C%2B%2B-multimap-solution-132-ms

https://leetcode.com/problems/maximum-frequency-stack/discuss/163453/JAVA-O(1)-solution-easy-understand-using-bucket-sort

[LeetCode All in One 题目讲解汇总(持续更新中...)](https://www.cnblogs.com/grandyang/p/4606334.html)

[LeetCode] 895. Maximum Frequency Stack 最大频率栈的更多相关文章

  1. LeetCode 895. Maximum Frequency Stack

    题目链接:https://leetcode.com/problems/maximum-frequency-stack/ 题意:实现一种数据结构FreqStack,FreqStack需要实现两个功能: ...

  2. 【LeetCode】895. Maximum Frequency Stack 解题报告(Python)

    [LeetCode]895. Maximum Frequency Stack 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxueming ...

  3. [Swift]LeetCode895. 最大频率栈 | Maximum Frequency Stack

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

  4. 最大频率栈 Maximum Frequency Stack

    2018-10-06 22:01:11 问题描述: 问题求解: 为每个频率创建一个栈即可. class FreqStack { Map<Integer, Integer> map; Lis ...

  5. LeetCode - Maximum Frequency Stack

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

  6. LeetCode OJ:Min Stack(最小栈问题)

    Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. pu ...

  7. Maximum Frequency Stack

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

  8. LeetCode Monotone Stack Summary 单调栈小结

    话说博主在写Max Chunks To Make Sorted II这篇帖子的解法四时,写到使用单调栈Monotone Stack的解法时,突然脑中触电一般,想起了之前曾经在此贴LeetCode Al ...

  9. Leetcode 946. Validate Stack Sequences 验证栈序列

    946. Validate Stack Sequences 题目描述 Given two sequences pushed and popped with distinct values, retur ...

随机推荐

  1. web.xml引入 xml (tomcat 7.0.52) 以上版本报错

    原文地址:https://blog.csdn.net/sdmxdzb/article/details/47728017?locationNum=11 今天在搞工作流,tomcat7.0.57 总是报错 ...

  2. 队列和 BFS —— 栈和 DFS

    队列和 BFS: 广度优先搜索(BFS)的一个常见应用是找出从根结点到目标结点的最短路径. 示例 这里我们提供一个示例来说明如何使用 BFS 来找出根结点 A 和目标结点 G 之间的最短路径. 洞悉 ...

  3. CompletableFuture1

    public class CompletableFutureTest { public static void main(String[] args) throws Exception { test5 ...

  4. class net.sf.cglib.core.DebuggingClassWriter overrides final method visit

    在使用CGLIB进行动态代理的时候,报了[java.lang.VerifyError: class net.sf.cglib.core.DebuggingClassWriter overrides f ...

  5. yii2.0的学习之旅(一)

    一. 通过composer安装yii2.0项目 *本文是根据您已经安装了composer (1)跳转到项目根目录 cd /xxxx/www (2)下载插件 composer global requir ...

  6. NET 特性(Attribute)

    NET 特性(Attribute) 转自 博客园(Fish) 特性(Attribute):是用于在运行时传递程序中各种元素(比如类.方法.结构.枚举.组件等)的行为信息的声明性标签. 您可以通过使用特 ...

  7. SQLAlchemy多表操作

    目录 SQLAlchemy多表操作 一对多 数据准备 具体操作 多对多 数据准备 操作 其它 SQLAlchemy多表操作 一对多 数据准备 models.py from sqlalchemy.ext ...

  8. JavaScript全局属性和全局函数

    JavaScript全局属性和全局函数可以与所有内置JavaScript对象一起使用. JavaScript全局属性 属性 描述 Infinity 表示正/负无穷大的数值 NaN "Not- ...

  9. 车间如何数字化?MES系统来助力

    对于生产过程复杂多变的离散制造企业而言,面临重重考验:生产作业计划频繁变更,制造工艺复杂,在生产过程中的临时插单.材料短缺等现象.通过MES制造执行管理解决方案,搭建协同管理平台,加强控制力.执行力和 ...

  10. AT+CNUM获取不到手机号

    原因是卡商没有写入SIM卡 解决办法 手动写入 1. 先确认SIM卡的本机号码 2. 选择电话本存储 /* AT+CPBS Select phonebook memory storage " ...