GuilinDev

Lc0716

05 August 2008

716 Max Stack

设计存储栈内最大值的栈

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
52
53
54
55
56
57
58
59
60
61
62
class MaxStack {
    List<Integer> stack;
    int max = Integer.MIN_VALUE;
    
    public MaxStack() {
        stack = new ArrayList<>();    
    }
    public void push(int x) {
         max = Math.max(x,max);
         stack.add(x);
    }
    
    public int pop() {
        int remove = stack.get(stack.size()-1);
        stack.remove(stack.size()-1);
        if(remove == max){
            getMax();
        }
        return remove;    
    }
    
    public int top() {
        if(!stack.isEmpty()) {
             return  stack.get(stack.size()-1);          
        }
        return -1;
        
    }

    public int peekMax() {
        return max;
    }
    public int popMax() {
        int idx = 0;
        for(int i = 0; i < stack.size(); i++) {
            if(stack.get(i) == max) idx = i;
        }
        stack.remove(idx);
        int oldMax= max; 
        getMax();
        
        return  oldMax;
    }
    public void getMax() {
        max = Integer.MIN_VALUE;
        for(int value : stack) {
            max = Math.max(max, value);
        }
        
        
    }
}

/**
 * Your MaxStack object will be instantiated and called as such:
 * MaxStack obj = new MaxStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.peekMax();
 * int param_5 = obj.popMax();
 */