Java 2 Arrays


  • 0
    public class MinStack {
        int size = 35; // set it to 100 t0 beat 98%, and this probably works.
        int[] stack = new int[size];
        int[] min = new int[size];
        int top = 0;
    
        public MinStack() {
        }
    
        public void push(int x) {
            if (top >= this.size) {
                this.size *= 2;
                this.stack = Arrays.copyOf(this.stack, this.size);
                this.min = Arrays.copyOf(this.min, this.size);
            }
    
            this.stack[top] = x;
            if (top == 0) {
                this.min[top] = x;
            } else {
                if (x < this.min[top-1])
                    this.min[top] = x;
                else
                    this.min[top] = this.min[top-1];
            }
            top++;
        }
    
        public void pop() {
            if (top > 0)
                top--;
        }
    
        public int top() {
            return this.stack[top-1];
        }
    
        public int getMin() {
            return this.min[top-1];
        }
    }
    

Log in to reply
 

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