您的位置:首页 > 其它

设计包含min函数的栈

2014-03-24 21:42 281 查看
题目:定义栈的数据结构,要求添加一个min函数,能够得到栈的最小元素。要求函数min、push以及pop的时间复杂度都是O(1)。

唉,又没想出来,fuck

参考地址:http://zhedahht.blog.163.com/blog/static/25411174200712895228171/

stack

维护一个额外的min_stack,这个min_stack里面存储最小值所在stack中的index(或者就存最小值也可以)。ps,这里还可以优化到只存储最小值的最小index,即如果有重复的值,则只保存最小的那个index即可。

举个例子演示上述代码的运行过程:

步骤 数据栈 辅助栈 最小值

1.push 3 3 0 3

2.push 4 3,4 0,0 3

3.push 2 3,4,2 0,0,2 2

4.push 1 3,4,2,1 0,0,2,3 1

5.pop 3,4,2 0,0,2 2

6.pop 3,4 0,0 3

7.push 0 3,4,0 0,0,2 0

这里贴一个自己写的只保存最小值的最小index的代码

int stack[10000];
int min_stack[10000];
int top = 0;
int min_top = 0;
void push(int n){
stack[top++] = n;
if(min_top==0)
min_stack[min_top++] =top-1;
else if(n<stack[min_stack[min_top-1]]){
min_stack[min_top++] = top-1;
}
}
int getMin(){
if(min_top==0)
return -1;
return stack[min_stack[min_top-1]];
}

int pop(){
if(top==0)
return -1;
int result = stack[--top];
if(min_stack[min_top-1]==top)
min_top--;
return result;
}


用栈来记录一些东西总是很美好的,比如leetcode中的一道题Largest Rectangle in Histogram 这个就和这个思路是一样的!呵呵,废柴,做过都不会
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: