鱼C论坛

 找回密码
 立即注册
查看: 852|回复: 2

[技术交流] c++刷剑指offer(面试题30. 包含min函数的栈)【栈】

[复制链接]
发表于 2020-4-2 19:56:00 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 糖逗 于 2020-5-8 18:04 编辑

题目描述:
  1. 定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。

  2.  

  3. 示例:

  4. MinStack minStack = new MinStack();
  5. minStack.push(-2);
  6. minStack.push(0);
  7. minStack.push(-3);
  8. minStack.min();   --> 返回 -3.
  9. minStack.pop();
  10. minStack.top();      --> 返回 0.
  11. minStack.min();   --> 返回 -2.
  12.  

  13. 提示:

  14. 各函数的调用总次数不超过 20000 次
  15.  

  16. 来源:力扣(LeetCode)
  17. 链接:https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof
  18. 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
复制代码



  1. #include <iostream>
  2. #include <stack>

  3. using namespace std;


  4. class MinStack {
  5. private:
  6.     stack<int> temp1;
  7.     stack<int> temp2;
  8. public:
  9.     /** initialize your data structure here. */
  10.     MinStack() {

  11.     }
  12.    
  13.     void push(int x) {
  14.         temp1.push(x);
  15.         if(temp2.empty() || temp2.top() >= x){
  16.             temp2.push(x);
  17.         }
  18.     }
  19.    
  20.     void pop() {
  21.         if(temp1.empty()) return;
  22.         if(temp1.top() == temp2.top()) temp2.pop();
  23.         temp1.pop();

  24.     }
  25.    
  26.     int top() {
  27.         return temp1.top();

  28.     }
  29.    
  30.     int min() {
  31.         return temp2.top();

  32.     }
  33. };


  34. int main(void){
  35.         MinStack temp;
  36.         temp.push(2);
  37.         temp.push(3);
  38.         temp.push(1);
  39.         cout << temp.min() << endl;
  40.         cout << "----------" << endl;
  41.         temp.pop();
  42.         cout << temp.min() << endl;
  43.         cout << "----------" << endl;       
  44.         return 0;
  45. }
复制代码



注意事项:
1.用temp2的顶端存储最小值。

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2020-4-2 19:58:11 | 显示全部楼层
  1. if(temp2.empty() || temp2.top() >= x)
复制代码


上面19行的代码一定要加上等号!!!!!!
因为,假如1是最小的数,且有2个1,从栈中去除1个1,当前最小值还是1。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-4-2 19:59:03 | 显示全部楼层
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-12 18:41

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表