包含min函数的栈

本文介绍了一种特殊的数据结构——栈,该栈能在O(1)的时间复杂度下实现push、pop及获取最小值的操作。通过维护两个数组,一个用于存储数据,另一个用于记录当前最小值的位置,确保了效率。

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

题目:定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的函数。在该栈中,调用min,push,pop的时间复杂度都为O(1)。

#include<iostream>
#include<vector>
using namespace std;
template <class T>
class Stack
{
public:
	void push(T  data)
	{
		if(_array.size()==0)
		{
			_array.push_back(data);
			_array1.push_back(0);
		}
		else
		{
			int index=_array1.size()-1;
			if(data>=_array[index])
			{
				_array.push_back(data);
				_array1.push_back(_array1[index]);
			}
			else
			{
				_array.push_back(data);
				_array1.push_back(index+1);
			}
		}
	}
	void pop()
	{
		int index=_array.size()-1;
		_array[index]=NULL;
		_array1[index]=NULL;
	}
	T Min()
	{
		int end=_array1.size()-1;
		int index=_array1[end];
		return _array[index];
	}
private:
	vector<T> _array;
	vector<int> _array1;
};
void test()
{
	Stack<int> s1;
	s1.push(3);
	s1.push(7);
	s1.push(4);
	s1.push(1);
	s1.push(8);
	s1.push(0);
	cout<<s1.Min()<<endl;

}
int main()
{
	test();
	system("pause");
	return 0;
}

结果:

wKiom1c4QzfQMbH7AAAgJWffcIg621.png

本文出自 “liveyoung” 博客,转载请与作者联系!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值