C ++
 Computer >> コンピューター >  >> プログラミング >> C ++

C ++で追加のスタックを使用せずに、O(1)でスタックの最大値を見つけます


スタックに最大の要素を格納できるスタックを作成するとします。そして、O(1)時間でそれを得ることができます。制約は、追加のスペースを使用してはならないため、O(1)の追加スペースです。

最大値を格納するユーザー定義スタックを1つ作成できます。ポップやピークなど、1つの操作が実行されると、最大値が返されます。ピーク操作の場合は、スタックトップの最大値と最大要素を返します。ポップ操作の場合は、トップ要素が大きい場合はそれを出力し、maxを2 * max –top_elementとして更新します。それ以外の場合はtop_elementを返します。プッシュ操作の場合、最大要素を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

  1. 二分探索を使用して配列内の最大要素を検索するC++プログラム

    これは、二分探索木を使用して配列の最大要素を見つけるためのC++プログラムです。このプログラムの時間計算量はO(log(n))です。 アルゴリズム Begin Construct the Binary Search Tree using the given data elements. Next traverse the root pointer to the rightmost child node available. Print the data part of the node as the maximum data element of the given data

  2. 線形検索を使用して配列内の最小要素を検索するC++プログラム

    これは、線形探索アプローチを使用して配列の最小要素を見つけるためのC++プログラムです。このプログラムの時間計算量はO(n)です。 アルゴリズム Begin Assign the data element to an array. Assign the value at ‘0’ index to minimum variable. Compare minimum with other data element sequentially. Swap values if minimum value is more then the value at