您的位置:首页 > 运维架构

设计一个有getMin(),push(),pop().功能的栈

2016-11-14 15:44 295 查看
要求:pop push getMin的时间复杂度O(1).

package chapter01_stack_and_queue;

import java.util.Stack;

public class _01_GetMinStack {
public static class MyStack {
Stack<Integer> stackData = new Stack<Integer>();
Stack<Integer> stackMin = new Stack<Integer>();

/**
* 申请另外一个栈一直存储最小值。与数据栈同步增长push
* @param newNum
*/
public void push(int newNum) {
if (this.stackMin.isEmpty()) {
this.stackMin.push(newNum);
} else if (newNum < this.getMin()) {
this.stackMin.push(newNum);
} else {
int newMin = this.stackMin.peek();
this.stackMin.push(newMin);
}
this.stackData.push(newNum);
}

public int pop() {
this.stackMin.pop();
return this.stackData.pop();
}

private int getMin() {
return this.stackMin.peek();
}
}

public static void main(String[] args) {
MyStack stack = new MyStack();
stack.push(3);
stack.push(4);
stack.push(1);
System.out.println(stack.getMin());
stack.pop();
System.out.println(stack.getMin());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  getMIn pop push O1