近期复习数据结构,看到网上有一道算法题,该题目曾经是google的一道面试题,国内的互联网公司也纷纷效仿。我也顺便复习之。
题目内容为:对现在的stack(栈)数据结构进行改进,加一个min()功能,使之能在常数,即o(1),时间内给出栈中的最小值。可对push()和pop()函数进行修改,但要求其时间复杂度都只能是o(1)。
解题思路:1.由于题目要求的是一个栈,所以想要通过栈内元素进行排序,这个是不可行的。
2.由于存在每次的push和pop操作。所以,通过在入口设置最小值,然后不断更新最小值的方式也是不可取的。因为,pop一次之后就失效了。
解决方案是通过辅助栈表,由于题目只要求获得栈内剩余元素中的最小值,并没有要求每次pop出来的是最小值,我自己就陷入了这个思维。所以我们可以通过辅助栈,即数据栈每push一次,辅助栈也push一次,push的值为数据栈中的当前最小值。经过如此,最后,辅助栈每次push就均可获得数据栈中的最小值。
下面提供相关的示例代码:
//
// main.cpp
// 栈最小值
//
//
#include <iostream>
#include <assert.h>
#include <deque>
using namespace std;
#define MAX_SIZE 100
template<typename T>//考虑到数据的多样性,采用模版
class DataStack {
T dataList[MAX_SIZE];
T minList[MAX_SIZE];
int top;//栈顶标记
public:
DataStack(){top = -1;}
void Push(T &value);
T Pop();
T GetMin();
};
template<typename T>
void DataStack<T>::Push(T &value){
top++;
dataList[top] = value;
if (top == 0) {
minList[top] = value;
}
else{
if (value < minList[top-1]) {
minList[top] = value;
}
else{
minList[top] = minList[top - 1];
}
}
};
template<typename T>
T DataStack<T>::Pop(){
minList[top] = 0;
return dataList[top--];
}
template <typename T>
T DataStack<T>::GetMin(){
return minList[top];
}
int main(int argc, const char * argv[]) {
// insert code here...
DataStack<int> dataList;
int temp=9;
dataList.Push(temp);
temp = 8;
dataList.Push(temp);
temp = 13;
dataList.Push(temp);
temp = 35;
dataList.Push(temp);
cout<<dataList.GetMin()<<endl;
dataList.Pop();
cout<<dataList.GetMin()<<endl;
dataList.Pop();
cout<<dataList.GetMin()<<endl;
dataList.Pop();
cout<<dataList.GetMin()<<endl;
dataList.Pop();
return 0;
}