Cheat beats 99%


  • 0
    L

    Anyway i dont think we should use Stack in this question cause we are supposed to design a stack.
    I used ArrayList.

    public class MinStack {
        List<Integer> list;
        int min = Integer.MAX_VALUE;
        /** initialize your data structure here. */
        public MinStack() {
           list = new ArrayList<>();
        }
        
        public void push(int x) {
            list.add(x);
            min = Math.min(min,x);
        }
        
        public void pop() {
            if (list.get(list.size()-1)==min){
                list.remove(list.size()-1);
                min = Integer.MAX_VALUE;
                int[] tmp = new int[list.size()];
                int index = 0;
                for (Integer i : list){
                    tmp[index] = i;
                    index ++;
                }
                for (int i = 0; i < tmp.length; i ++){
                    min = Math.min(min, tmp[i]);
                }
            } else list.remove(list.size()-1);
            
        }
        
        public int top() {
            return list.get(list.size()-1);
        }
        
        public int getMin() {
            return min;
        }
    }
    
    /**
     * Your MinStack object will be instantiated and called as such:
     * MinStack obj = new MinStack();
     * obj.push(x);
     * obj.pop();
     * int param_3 = obj.top();
     * int param_4 = obj.getMin();
     */
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.