2. 微软面试题:设计包含min函数的栈(栈)

 定义栈的数据结构,要求添加一个min函数,能够得到栈的最小元素。 要求函数min、push以及pop的时间复杂度都是O(1)。


这个题的关键是设计min时间复杂度为O(1)的函数,通常min函数的复杂度为O(n)。


可以使用空间换时间的策略,加一个栈来维护min函数值,每一次pop栈,min函数对应的栈也相应进行操作。


下面看个例子:

push:

7,5,2,8,3,1

对应min栈的为:

7,5,2,2,2,1


程序实现如下:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;

template <int maxsize=1024> 
class Stack{
private:
	int data1[maxsize];
	int data[maxsize];
	int end;
	int m;
public:
	Stack():end(0),m(0){}
	bool empty()
	{
		if( end == 0)
			return true;
		else
			return false;
	}
	bool full()
	{
		if( end == maxsize -1) return true;
		else
			return false;
	}
	bool pop(int& t)
	{
		if(empty()) return false;
		end = end -1;
		t = data[end];
		return true;
	}
	bool push(int t)
	{
		if(full()) return false;
		if(empty() || m>t) m = t;
		data1[end] = m;
		data[end] = t;
		end += 1;
		return true;
	}
	int min()
	{
		if(empty()) return -1;
		else
			return data1[end -1];
	}
};


int main()
{
	Stack<1024> s;
	//7,5,2,8,3,1
	s.push(7);
	s.push(5);
	s.push(2);
	s.push(8);
	s.push(3);
	s.push(1);
	string fstr = "7,5,2,8,3,1";
	string str;
	string mstr;
	while(!s.empty())
	{
		int i = 0;
		int m = 0;
		char chr[10];
		string str1 = "";
		m = s.min();
		memset(chr, 0, 10);
		sprintf(chr, "%d", m);
		str1 = chr;
		mstr += str1 + ",";
		s.pop(i);
		memset(chr, 0, 10);
		sprintf(chr, "%d", i);
		str1 = chr;
		str += str1 + ",";
		
		//cout << i << ",";
	}
	cout << "begin status: " << fstr.c_str() << endl;
	cout << "pop: " << str.c_str() << endl;
	cout << "min: " << mstr.c_str() << endl;
	return 0;
}


打印结果为:

begin status: 7,5,2,8,3,1
pop: 1,3,8,2,5,7,
min: 1,2,2,2,5,7,

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值