当前位置:   article > 正文

编程之美-队列中取最大值操作问题_有一个队列支持入队、出队、查找队首元素、查找队中最大值的操作,请编程实现这个

有一个队列支持入队、出队、查找队首元素、查找队中最大值的操作,请编程实现这个

  1. /*
  2. * Usage:
  3. * ./stack_queue <input.txt
  4. *
  5. * input.txt:
  6. * 10 3 4 1 7
  7. */
  8. #include<iostream>
  9. #include<stack>
  10. #include<algorithm>
  11. using namespace std;
  12. #define MAXNUM 100000
  13. struct StackGetMin {
  14. void push(int x) {
  15. elements.push(x);
  16. if (minStack.empty() || x <= minStack.top())
  17. minStack.push(x);
  18. }
  19. bool pop() {
  20. if (elements.empty()) return false;
  21. if (elements.top() == minStack.top())
  22. minStack.pop();
  23. elements.pop();
  24. return true;
  25. }
  26. bool getMin(int &min) {
  27. if (minStack.empty()) {
  28. return false;
  29. } else {
  30. min = minStack.top();
  31. return true;
  32. }
  33. }
  34.   bool empty() {                                                                            
  35.     if(minStack.empty())
  36.       return true;
  37.     else
  38.       return false;
  39.   }
  40.   int top() {
  41.     return elements.top();
  42.   }
  43.   stack<int> elements;
  44.   stack<int> minStack;
  45. };
  46. struct minQueue {
  47.   bool getMin(int &m) {
  48.     int a,b;
  49.     if(!A.getMin(a)) a = MAXNUM;
  50.     if(!B.getMin(b)) b = MAXNUM;
  51.     m = min(a,b);
  52.     return true;
  53.   }
  54.   void enqueue(int x) {
  55.     B.push(x);
  56.   }
  57.   int dequeue() {
  58.     if (A.empty()) {
  59.       while(!B.empty()) {
  60.         A.push(B.top());
  61.         B.pop();
  62.       }
  63.     }
  64.     int ret = A.top();
  65.     A.pop();
  66.     return ret;                                                

书中给出了三种解法,分别是传统方法、最大堆和用双栈的方法。其中,第三种解法满足了入队、出队和取最大值都是O(1)的条件。基于[1],测试了一下。


代码:



参考资料

1. http://www.leetcode.com/2010/11/stack-that-supports-push-pop-and-getmin.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/960752
推荐阅读
相关标签
  

闽ICP备14008679号