Coursera Algorithms week2 栈和队列 练习测验: Stack with max

题目原文:

Stack with max. Create a data structure that efficiently supports the stack operations (push and pop) and also a return-the-maximum operation. Assume the elements are reals numbers so that you can compare them.

分析:

该题目要求在实现正常stack的push和pop操作外,还需要实现返回maximum的操作,显然一个数组是不够的,需要额外的数组maximums[]来从小到大存储stack内的值,每次返回maximum就返回maximums[n-1],可满足要求。

 1 import java.util.Arrays;
 2 
 3 /**
 4  * @author evasean www.cnblogs.com/evasean/
 5  */
 6 public class StackWithMax {
 7     public double[] items;// 为了方便展示结果,我也懒得写遍历方法,就设为public
 8     public double[] maximums; // 存放最大值的数组,为了方便展示结果,我也懒得写遍历方法,就设为public
 9     private int n;
10     private int cap;
11 
12     public StackWithMax() {
13         n = 0;
14         cap = 2;
15         items = new double[cap];
16         maximums = new double[cap];
17     }
18 
19     public boolean isEmpty() {
20         return n == 0;
21     }
22 
23     public void push(double item) {
24         if (n == 0)
25             maximums[0] = item;
26         else {
27             int i;
28             int j;
29             for (i = n - 1; i >= 0; i--) {// 这个循环用来找出item在maximums数组中应该放置的位置
30                 if (item <= maximums[i])
31                     continue;
32                 else
33                     break;
34             }
35             for (j = n - 1; j > i; j--) {// 将位置i以后的元素都往后挪一个位置
36                 maximums[j + 1] = maximums[j];
37             } // 循环结束时j指向i
38             maximums[j + 1] = item;// j+1就是item应该放置的位置
39         }
40         items[n++] = item;
41         if (n == cap)
42             resize(2 * cap);
43     }
44 
45     public double pop() {
46         double item = items[--n];
47         if (n > 0 && n == cap / 4)
48             resize(cap / 2);
49         return item;
50     }
51 
52     public double maximum() {
53         return maximums[n - 1];
54     }
55 
56     private void resize(int cap) {
57         double[] t1 = new double[cap];
58         double[] t2 = new double[cap];
59         for (int i = 0; i < n; i++) {
60             t1[i] = items[i];
61             t2[i] = maximums[i];
62         }
63         items = t1;
64         maximums = t2;
65         this.cap = cap;
66     }
67 
68     public static void main(String[] args) {
69         StackWithMax stack = new StackWithMax();
70         stack.push(9);
71         stack.push(8);
72         stack.push(11);
73         stack.push(0);
74         stack.push(-9.9);
75         stack.push(88);
76         System.out.println(Arrays.toString(stack.items));
77         System.out.println(Arrays.toString(stack.maximums));
78         stack.pop();
79         System.out.println(stack.maximum());
80     }
81 }

 

转载于:https://www.cnblogs.com/evasean/p/7230112.html

你可能感兴趣的:(Coursera Algorithms week2 栈和队列 练习测验: Stack with max)