在不使用额外的栈的情况下,在 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
广告
数据结构
网络
关系型数据库
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP