题目
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
知识点
栈
思路
解法一、
push和pop可以直接用java.util.Stack中的方法(pop稍微有区别,这个类中的pop方法不返回参数);
top()可以用peek()方法;
min()则新开一个s2栈,暂存s1,遍历s1找到最小值再返回。
解法二、
在push时就找到最小值存为全局变量,若有新的最小值,则将第二小的值也存入栈;
pop时,若pop值为最小值,则再pop一次,将此时的值(第二小的值)设为minNum最小值。
调用min()时返回minNum。
代码
import java.util.Stack;
public class Solution {
private static Stack<Integer> s1 = new Stack<Integer>();
public void push(int node) {
s1.push(node);
}
public void pop() {
s1.pop();
}
public int top() {
return (int)s1.peek();
}
public int min() {
int num = s1.size();
int min=100000000;
Stack s2 = new Stack();
for(int i=0;i<num;i++){
int a = top();
if(a<min) min=a;
s2.push(a);
pop();
}
for(int i=0;i<num;i++){
int a = (int)s2.pop();
push(a);
}
return min;
}
}
import java.util.Stack;
public class Solution {
private static Stack<Integer> s = new Stack<Integer>();
private int minNum = Integer.MAX_VALUE;
public void push(int node) {
if(s.empty()){
s.push(node);
minNum = node;
}
else{
if(minNum>node){
s.push(minNum);
minNum = node;
}
s.push(node);
}
}
public void pop() {
if(s.pop()==minNum){
minNum = s.pop();
}
}
public int top() {
return (int)s.peek();
}
public int min() {
return minNum;
}
}