Design a max stack that supports push, pop, top, peekMax and popMax.

  1. push(x) -- Push element x onto stack.
  2. pop() -- Remove the element on top of the stack and return it.
  3. top() -- Get the element on the top.
  4. peekMax() -- Retrieve the maximum element in the stack.
  5. popMax() -- Retrieve the maximum element in the stack, and remove it. If you find more than one maximum elements, only remove the top-most one.

Example 1:

  1. MaxStack stack = new MaxStack();
  2. stack.push(5);
  3. stack.push(1);
  4. stack.push(5);
  5. stack.top(); -> 5
  6. stack.popMax(); -> 5
  7. stack.top(); -> 1
  8. stack.peekMax(); -> 5
  9. stack.pop(); -> 1
  10. stack.top(); -> 5

Note:

  1. -1e7 <= x <= 1e7
  2. Number of operations won't exceed 10000.
  3. The last four operations won't be called when stack is empty.

这道题让我们实现一个最大栈,包含一般栈的功能,但是还新加了两个功能peekMax()和popMax(),随时随地可以查看和返回最大值。之前有一道很类似的题Min Stack,所以我们可以借鉴那道题的解法,使用两个栈来模拟,s1为普通的栈,用来保存所有的数字,而s2为最大栈,用来保存出现的最大的数字。

在push()函数中,我们先来看s2,如果s2为空,或者s2的栈顶元素小于等于x,将x压入s2中。因为s2保存的是目前为止最大的数字,所以一旦新数字大于等于栈顶元素,说明遇到更大的数字了,压入栈。然后将数组压入s1,s1保存所有的数字,所以都得压入栈。

在pop()函数中,当s2的栈顶元素和s1的栈顶元素相同时,我们要移除s2的栈顶元素,因为一个数字不在s1中了,就不能在s2中。然后取出s1的栈顶元素,并移除s1,返回即可。

在top()函数中,直接返回s1的top()函数即可。

在peekMax()函数中,直接返回s2的top()函数即可。

在popMax()函数中,先将s2的栈顶元素保存到一个变量mx中,然后我们要在s1中删除这个元素,由于栈无法直接定位元素,所以我们用一个临时栈t,将s1的出栈元素保存到临时栈t中,当s1的栈顶元素和s2的栈顶元素相同时退出while循环,此时我们在s1中找到了s2的栈顶元素,分别将s1和s2的栈顶元素移除,然后要做的是将临时栈t中的元素加回s1中,注意此时容易犯的一个错误是,没有同时更新s2,所以我们直接调用push()函数即可,参见代码如下:

解法一:

  1. class MaxStack {
  2. public:
  3. /** initialize your data structure here. */
  4. MaxStack() {}
  5.  
  6. void push(int x) {
  7. if (s2.empty() || s2.top() <= x) s2.push(x);
  8. s1.push(x);
  9. }
  10.  
  11. int pop() {
  12. if (!s2.empty() && s2.top() == s1.top()) s2.pop();
  13. int t = s1.top(); s1.pop();
  14. return t;
  15. }
  16.  
  17. int top() {
  18. return s1.top();
  19. }
  20.  
  21. int peekMax() {
  22. return s2.top();
  23. }
  24.  
  25. int popMax() {
  26. int mx = s2.top();
  27. stack<int> t;
  28. while (s1.top() != s2.top()) {
  29. t.push(s1.top()); s1.pop();
  30. }
  31. s1.pop(); s2.pop();
  32. while (!t.empty()) {
  33. push(t.top()); t.pop();
  34. }
  35. return mx;
  36. }
  37.  
  38. private:
  39. stack<int> s1, s2;
  40. };

下面这种解法没有利用一般的stack,而是建立一种较为复杂的数据结构,首先用一个list链表来保存所有的数字,然后建立一个数字和包含所有相同的数字的位置iterator的向量容器的映射map。

在push()函数中,把新数字加到list表头,然后把数字x的位置iterator加到数字映射的向量容器的末尾。

在pop()函数中,先得到表头数字,然后把该数字对应的iterator向量容器的末尾元素删掉,如果此时向量容器为空了,将这个映射直接删除,移除表头数字,返回该数字即可。

在top()函数中,直接返回表头数字即可。

在peekMax()函数中,因为map是按key值自动排序的,直接尾映射的key值即可。

在popMax()函数中,首先保存尾映射的key值,也就是最大值到变量x中,然后在其对应的向量容器的末尾取出其在list中的iterator。然后删除该向量容器的尾元素,如果此时向量容器为空了,将这个映射直接删除。根据之前取出的iterator,在list中删除对应的数字,返回x即可,参见代码如下:

解法二:

  1. class MaxStack {
  2. public:
  3. /** initialize your data structure here. */
  4. MaxStack() {}
  5.  
  6. void push(int x) {
  7. v.insert(v.begin(), x);
  8. m[x].push_back(v.begin());
  9. }
  10.  
  11. int pop() {
  12. int x = *v.begin();
  13. m[x].pop_back();
  14. if (m[x].empty()) m.erase(x);
  15. v.erase(v.begin());
  16. return x;
  17. }
  18.  
  19. int top() {
  20. return *v.begin();
  21. }
  22.  
  23. int peekMax() {
  24. return m.rbegin()->first;
  25. }
  26.  
  27. int popMax() {
  28. int x = m.rbegin()->first;
  29. auto it = m[x].back();
  30. m[x].pop_back();
  31. if (m[x].empty()) m.erase(x);
  32. v.erase(it);
  33. return x;
  34. }
  35.  
  36. private:
  37. list<int> v;
  38. map<int, vector<list<int>::iterator>> m;
  39. };

类似题目:

Min Stack

参考资料:

https://discuss.leetcode.com/topic/110014/c-using-two-stack

https://discuss.leetcode.com/topic/110066/c-o-logn-for-write-ops-o-1-for-reads

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Max Stack 最大栈的更多相关文章

  1. [leetcode]716. Max Stack 最大栈

    Design a max stack that supports push, pop, top, peekMax and popMax. push(x) -- Push element x onto ...

  2. [LeetCode] Min Stack 最小栈

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

  3. LeetCode Max Stack

    原题链接在这里:https://leetcode.com/problems/max-stack/description/ 题目: Design a max stack that supports pu ...

  4. LeetCode Min Stack 最小值栈

    题意:实现栈的四个基本功能.要求:在get最小元素值时,复杂度O(1). 思路:链表直接实现.最快竟然还要61ms,醉了. class MinStack { public: MinStack(){ h ...

  5. [LeetCode] 155. Min Stack 最小栈

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

  6. LeetCode 155:最小栈 Min Stack

    LeetCode 155:最小栈 Min Stack 设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈. push(x) -- 将元素 x 推入栈中. pop() -- ...

  7. 【LeetCode】716. Max Stack 解题报告(C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 双栈 日期 题目地址:https://leetcode ...

  8. leetcode Maximal Rectangle 单调栈

    作者:jostree 转载请注明出处 http://www.cnblogs.com/jostree/p/4052721.html 题目链接:leetcode Maximal Rectangle 单调栈 ...

  9. [CareerCup] 3.2 Min Stack 最小栈

    3.2 How would you design a stack which, in addition to push and pop, also has a function min which r ...

随机推荐

  1. wipefs进程

    wipefs进程是啥,占用了百分之90多的cpu wipefs进程是啥,占用了百分之90多的cpu,把这个进程干掉了,过了一天又自动启动了,很多朋友应该遇到过类似的问题. wipefs是linux自带 ...

  2. C#中的String类

    一.String类的方法 1. Trim():清除字符串两端的空格 2. ToLower():将字符串转换为小写 3. Equals():比较两个字符串的值,bool 4. IndexOf(value ...

  3. Python中的PYTHONPATH环境变量

    PYTHONPATH是Python中一个重要的环境变量,用于在导入模块的时候搜索路径.可以通过如下方式访问: >>> import sys >>> sys.path ...

  4. 第二届强网杯-simplecheck

    这次强网杯第一天做的还凑合,但第二天有事就没时间做了(也是因为太菜做不动),这里就记录一下一道简单re-simplecheck(一血). 0x00 大致思路: 用jadx.gui打开zip可以看到,通 ...

  5. codevs 1283 等差子序列

    http://codevs.cn/problem/1283/ 题目描述 Description 给一个 1 到 N 的排列{Ai},询问是否存在 1<=p1<p2<p3<p4& ...

  6. mint-ui在vue中的使用。

    首先放上mint-ui中文文档 近来在使用mint-ui,发现部分插件在讲解上并不是很详细,部分实例找不到使用的代码.github上面的分享,里面都是markdown文件,内容就是网上的文档 刚好自己 ...

  7. margin-top导致父标签偏移问题

    从一个大神博客中看到这句话: 这个问题发生的原因是根据规范,一个盒子如果没有上补白(padding-top)和上边框(border-top),那么这个盒子的上边距会和其内部文档流中的第一个子元素的上边 ...

  8. Python模块configparser(操作配置文件ini)

    configparser模块提供对ini文件的增删改查方法. ini文件的数据格式: [name1] attribute1=value1 attribute2=value2 [name2] attri ...

  9. centos7 安装docker

    1.首先cent7 基本是在vm上完全安装'. 2.参考官方网站安装 1.https://wiki.centos.org/AdditionalResources/Repositories OS req ...

  10. c 语言的基本语法

    1,c的令牌(Tokens) printf("Hello, World! \n"); 这五个令牌是: printf ( "Hello, World! \n" ) ...