package SwordOffer;
import java.util.Stack;
/**
* @Description: 定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.min(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.min(); --> 返回 -2.
提示:
各函数的调用总次数不超过 20000 次
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
* @Param:
* @return:
* @Author: lvhong
* @Date:
* @E-mail lvhong282@163.com
*/
public class lab30easy {
class MinStack {
//使用辅助栈
Stack<Integer> a,b;
/** initialize your data structure here. */
public MinStack() {
a= new Stack();
b= new Stack();
}
public void push(int x) {
a.push(x);
if(b.empty()||x<=b.peek()){
b.push(x);
}
}
public void pop() {
if(a.peek().equals(b.peek())){
b.pop();
}
a.pop();
}
public int top() {
return a.peek();
}
public int min() {
return b.peek();
}
}
//使用辅助链表
// public MinStack() {
// }
// public void push(int x) {
// if (head == null)
// head = new Node(x, x, null);
// else
// head = new Node(x, Math.min(head.min, x), head);
// }
// public void pop() {
// head = head.next;
// }
// public int top() {
// return head.val;
// }
// public int min() {
// return head.min;
// }
// private class Node {
// int val;
// int min;
// Node next;
// public Node(int val, int min, Node next) {
// this.val = val;
// this.min = min;
// this.next = next;
// }
// }
//这个是只针对min的准确性做得特解,实际上pop和push,以及top处的元素都有问题
// class MinStack {//push方法可能会加入很多min
// int min = Integer.MAX_VALUE;
// Stack<Integer> stack = new Stack<>();
// public void push(int x) {
// //如果加入的值小于最小值,要更新最小值
// if (x <= min) {
// stack.push(min);
// min = x;
// }
// stack.push(x);
// }
// public void pop() {
// //如果把最小值出栈了,就更新最小值
// if (stack.pop() == min)
// min = stack.pop();
// }
// public int top() {
// return stack.peek();
// }
// public int min() {
// return min;
// }
// }
// 作者:sdwwld
// 链接:https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof/solution/jian-zhi-offer-30-bao-han-minhan-shu-de-zhan-tu-we/
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.min();
*/
}