您的当前位置:首页正文

最小栈问题(空间换时间O(1)复杂度)

来源:爱站旅游
导读最小栈问题(空间换时间O(1)复杂度)

设计一个支持push,pop,top操作,并能在常数时间内检索到最小元素的栈O(1)。

push(x) —— 将元素x推入栈中

pop() —— 删除栈顶的元素

top() —— 获取栈顶的元素

getMin() —— 检索栈中的最小元素

#include<bits/stdc++.h>

using namespace std;

stack<int>s,t;

void push(int x)
{
	s.push(x);
	if(t.empty())
		t.push(x);
	else
	 	t.push(min(x,t.top()));
}

void pop()
{
	if(!s.empty())s.pop();
	if(!t.empty())t.pop();
}

int top()
{
	return s.top();	
}

int getMin()
{
	return t.top();
}

int main()
{
	int n;
	scanf("%d",&n);
	for(int i = 1; i <= n; i ++)
	{
		int t;
		scanf("%d",&t);
		push(t);
	}
	
	printf("%d",getMin());
	return 0;
}

#include<bits/stdc++.h>

using namespace std;

stack<int>s,t;

void push(int x)
{
	s.push(x);
	if(t.empty())
		t.push(x);
	else
	 	t.push(min(x,t.top()));
}

void pop()
{
	if(!s.empty())s.pop();
	if(!t.empty())t.pop();
}

int top()
{
	return s.top();	
}

int getMin()
{
	return t.top();
}

int main()
{
	int n;
	scanf("%d",&n);
	for(int i = 1; i <= n; i ++)
	{
		string s;
		cin >> s;
		if(s.compare("push")==0)
		{
			int a;
			scanf("%d",&a);
			push(a);
		}
		if(s.compare("pop")==0)
		{
			pop();
		}
		if(s.compare("getMin")==0)
		{
			printf("%d",getMin());
		}
	}
	
	return 0;
}

 

 

 

因篇幅问题不能全部显示,请点此查看更多更全内容

Top