在不使用額外的棧的情況下,在 O(1) 中找到棧中的最大值


假設我們要製作一個能儲存棧中最大元素的棧。且要在 O(1) 時間內獲取最大值。限制條件是它不能使用任何額外空間(O(1) 額外空間)。

我們可以製作一個使用者定義的棧,它將儲存最大值。當執行一個操作(例如彈出或檢視)時,將返回最大值。對於檢視操作,返回棧頂和最大元素中的最大值,對於彈出操作,當棧頂元素較大時,然後列印它並更新 max 為 2*max – top_element。否則返回 top_element。對於壓入操作,更新 max 元素為 x(要插入的資料)和 2*x – max。

示例

 線上演示

#include <iostream>
#include <stack>
using namespace std;
class CustomStack {
   stack<int> stk;
   int stack_max;
   public:
   void getMax() {
      if (stk.empty())
         cout << "Stack is empty"<<endl;
      else
         cout << "Maximum Element in the stack is: "<< stack_max <<endl;
   }
   void peek() {
      if (stk.empty()) {
         cout << "Stack is empty ";
         return;
      }
      int top = stk.top(); // Top element.
      cout << "Top Most Element is: "<<endl;
      (top > stack_max) ? cout << stack_max : cout << top;
   }
   void pop() {
      if (stk.empty()) {
         cout << "Stack is empty"<<endl;
         return;
      }
      cout << "Top Most Element Removed: ";
      int top = stk.top();
      stk.pop();
      if (top > stack_max) {
         cout << stack_max <<endl;
         stack_max = 2 * stack_max - top;
      } else
         cout << top <<endl;
   }
   void push(int element) {
      if (stk.empty()) {
         stack_max = element;
         stk.push(element);
         cout << "Element Inserted: " << element <<endl;
         return;
      }
      if (element > stack_max) {
         stk.push(2 * element - stack_max);
         stack_max = element;
      } else
      stk.push(element);
      cout << "Element Inserted: " << element <<endl;
   }
};
int main() {
   CustomStack stk;
   stk.push(4);
   stk.push(6);
   stk.getMax();
   stk.push(8);
   stk.push(20);
   stk.getMax();
   stk.pop();
   stk.getMax();
   stk.pop();
   stk.peek();
}

輸出

Element Inserted: 4
Element Inserted: 6
Maximum Element in the stack is: 6
Element Inserted: 8
Element Inserted: 20
Maximum Element in the stack is: 20
Top Most Element Removed: 20
Maximum Element in the stack is: 8
Top Most Element Removed: 8
Top Most Element is:
6

更新日期:2019 年 12 月 17 日

522 次瀏覽

開啟您的 職業

完成課程以獲得認證

開始
廣告