常数时间内求栈的最大值

本文介绍了一种利用辅助栈在常数时间内获取栈中最大值的方法。当元素入栈时,只有当其大于或等于当前最大值时才将其推入辅助栈。出栈时,如果出栈元素与最大值相同,辅助栈也同步出栈。详情可参考相关链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//
//
// 奇数在前,偶数在后,
#include <iostream>
#include <assert.h>
#include <algorithm>
#include <stack>
#include <vector>
using namespace std;


int main()
{
	int an[]={4,2,5,7,12,6,12,3,21};
	stack<int,vector<int> >sta1;
	stack<int,vector<int> >sta2;
	int i;


	// 更小空间的栈
	cout<<"push:"<<endl;
	for (i=0; i<sizeof(an)/sizeof(int); i++)
	{
		sta1.push(an[i]);
		if (sta2.empty())
		{
			sta2.push(an[i]);
		}
		if (an[i]>=sta2.top())
		{
			sta2.push(an[i]);
		}
		cout<<"TopA: "<<sta1.top()<<" SizeA: "<<sta1.size()<<"  TopB: "<<sta2.top()<<"  SizeB: "<<sta2.size()<<endl;

	}
	cout<<endl<<endl<<"pop: "<<endl;
	while (!sta1.empty())
	{
		cout<<"TopA: "<<sta1.top()<<" TopB: "<<sta2.top()<<endl;
		int t=sta1.top();
		sta1.pop();
		if (t==sta2.top())
		{
			sta2.pop();
		}
	}
	return 0;
}


 

利用辅助堆栈。

入栈时,如果小于当前最大值,则辅助栈不动;如果大于或等于当前最大值,则辅助栈将该数push进来。

出栈时,如果top()处的数与当前最大值相同,则辅助栈也要出栈。

 

 

参考: http://www.cppblog.com/csolay/archive/2011/10/22/158858.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值