设计包含min函数的栈

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

这道题是我去年参加百度笔试时做的一道题,当时一点头绪都没有,这道题也就没有写。后来上网google一下,这原来是google早些年的一道面试题,难怪我这种菜鸟做不出来!

参考网上别人的思路,自己也有了点眉目:

在栈里添加一个成员变量存放最小元素(或者最小元素的位置,考虑到元素可以是其他复杂的数据类型,因此存在最小元素的位置更能减少存储空间)。每次push一个新元素进栈的时候,如果该元素比当前的最小元素还要小,则更新最小元素。但这个思路存在一个重要的问题,如果当前最小元素被pop出去,如何才能得到下一个最小元素?

因此仅仅添加一个成员变量存放最小元素是不够的,我们需要一个辅助栈,每次push一个新元素的时候,同时将最小元素push到辅助本中;每次pop一个元素出栈的时候,同时pop辅助栈。具体代码如下:

StackWithMin
1 package com.yuchao.stackwithmin;
2
3  import java.util.EmptyStackException;
4  import java.util.Stack;
5 import java.util.Vector;
6
7
8 public class StackWihMin<E extends Comparable<E>> extends Vector<E> {
9
10 /**
11 *
12 */
13 private static final long serialVersionUID = -1646397321796329267L;
14
15 //存储最小元素的位置
16 private Stack<Integer> minPosStack=new Stack<Integer>();
17
18 /**
19 * 栈的最小元素
20 * @return 最小元素
21 */
22 public E min()
23 {
24 return super.get(this.minPosStack.peek());
25 }
26
27 /**
28 * 入栈
29 * @param item
30 */
31 public synchronized void push(E item)
32 {
33 if(0==super.size())
34 {
35 this.minPosStack.push(0);
36 }
37 else
38 {
39 if(item.compareTo(min())<=0)
40 {
41 this.minPosStack.push(super.size());
42 }
43 else
44 {
45 this.minPosStack.push(this.minPosStack.peek());//维持不变
46 }
47 }
48 super.add(item);
49 }
50
51 /**
52 * 出栈
53 * @return 栈顶元素
54 */
55 public synchronized E pop()
56 {
57 E obj=null;
58 if(0==super.size())
59 throw new EmptyStackException();
60 obj=super.get(super.size()-1);
61 super.remove(super.size()-1);
62 this.minPosStack.pop();
63 return obj;
64 }
65
66 public synchronized void print()
67 {
68 if(0==super.size())
69 {
70 System.out.println("HashCode:"+this.hashCode()+";空栈;");
71 return;
72 }
73 System.out.print("HasCode:"+this.hashCode()+";栈");
74
75 for(int i=0;i<super.size();i++)
76 {
77 System.out.print(super.get(i)+" ");
78 }
79 System.out.println();
80
81 }
82
83
84
85 }
测试用例
1 package com.yuchao.stackwithmin;
2
3  public class Program {
4
5 /**
6 * @param args
7 */
8 public static void main(String[] args) {
9 // TODO Auto-generated method stub
10 StackWihMin<Integer> stackWihMin=new StackWihMin<Integer>();
11
12 stackWihMin.push(new Integer(3));
13 stackWihMin.push(new Integer(6));
14 stackWihMin.push(new Integer(2));
15 stackWihMin.push(new Integer(7));
16 stackWihMin.push(new Integer(1));
17 stackWihMin.push(new Integer(8));
18
19 stackWihMin.pop();
20 stackWihMin.pop();
21 stackWihMin.print();
22 System.out.println("Min():"+stackWihMin.min());
23
24 }
25
26 }
原文地址:https://www.cnblogs.com/yuchao/p/1963844.html