1. 程式人生 > >LeetCode:155. Min Stack(找出棧中最小的那個值)

LeetCode:155. Min Stack(找出棧中最小的那個值)

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • getMin() -- Retrieve the minimum element in the stack.

Example:

MinStack minStack = new MinStack();

minStack.push(-2);

minStack.push(0);

minStack.push(-3);

minStack.getMin(); --> Returns -3.

minStack.pop();

minStack.top(); --> Returns 0.

minStack.getMin(); --> Returns -2. 


方法1:(利用棧的形式,這個比較好想到,也是比較習慣的方式)

class MinStack {

    /** initialize your data structure here. */
    
    Stack<Integer> s=new Stack<>();
    private int min=Integer.MAX_VALUE;
    
    public void push(int x) {
        s.push(x);
        if (x < min) {
            min = x;
        }
    }
    
    public void pop() {
        min=Integer.MAX_VALUE;
        s.pop();
        for(int ele:s){
            if(ele<min){
                min=ele;
            }
        }   
    }
    
    public MinStack() {
        
    }
    public int top() {
        return s.peek();   
    }
    
    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();
 */

時間複雜度:O(n)

空間複雜度:O(1)


方法2:利用連結串列的形式,維護著棧的平衡

class MinStack {
    private int min = Integer.MAX_VALUE;
    private Node head;
    
    public class Node {
        int val;
        Node next;
        
        public Node(){}
        
        public Node(int val) {
            this.val = val;
        }
    }
	
    public MinStack() {
        
    }
    
    public void push(int x) {
        if (head == null) {
            head = new Node(x);
        } else {
            Node n = new Node(x);
            n.next = head;
            head = n;
        }
        if (x < min) {
            min = x;
        }
    }
    
    public void pop() {
        if (head != null) {
            head = head.next;
            min = Integer.MAX_VALUE;
            Node cur = head;
            while (cur != null) {
                if (cur.val < min) {
                    min = cur.val;
                }
                cur = cur.next;
            }            
        }
    }
    
    public int top() {
        return head.val;   
    }
    
    public int getMin() {
        return min;
    }
}

時間複雜度:O(n)

空間複雜度:O(n)