java栈,获取最小值GetMin方法。要求时间复杂度为O(1)
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52import java.util.Stack; public class MINSTACK { private Stack<Integer> mainStark=new Stack<Integer>(); private Stack<Integer> minStark=new Stack<Integer>(); /** * 入栈元素 * @param element */ public void push(int element){ mainStark.push(element); /**如果minStark为空或者当element值小于Minstark栈顶的值 *minStark也入栈当前元素 */ if (minStark.empty()||element<=minStark.peek()){ minStark.push(element); } } /** * 出栈操作 * @return */ public Integer pop(){ //查看两个栈的栈顶,如果最小栈与主栈相同。则最小栈同时出栈 if (mainStark.peek().equals(minStark.peek())){ minStark.pop(); } return mainStark.pop(); } public int getMin()throws Exception{ if (mainStark.empty()){ throw new Exception("Stack is empty"); } return minStark.peek(); } public static void main(String[] args) throws Exception { MINSTACK stack =new MINSTACK();stack.push(4); stack.push(4); stack.push(9); stack.push(7); stack.push(3); stack.push(8); stack.push(5); System.out.println(stack.getMin()); stack.pop(); stack.pop(); stack.pop(); stack.pop(); System.out.println(stack.getMin()); } }
时间复杂度为O(1),空间复杂度最坏情况下为O(n)
最后
以上就是甜甜可乐最近收集整理的关于java栈,获取最小值GetMin方法。要求时间复杂度为O(1)的全部内容,更多相关java栈内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复