
這題需要製作 MinStack 這個資料結構。
LeetCode 題目連結
https://leetcode.com/problems/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 1:
Input ["MinStack","push","push","push","getMin","pop","top","getMin"] [[],[-2],[0],[-3],[],[],[],[]] Output [null,null,null,null,-3,null,0,-2] Explanation MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0); minStack.push(-3); minStack.getMin(); // return -3 minStack.pop(); minStack.top(); // return 0 minStack.getMin(); // return -2
Constraints:
- Methods 
pop,topandgetMinoperations will always be called on non-empty stacks. 
Accept 作法
Runtime: 119 ms
Memory: 41.6 MB
Java 程式碼
class MinStack {
    ArrayList<Integer> stack;
    /** initialize your data structure here. */
    public MinStack() {
        stack  = new ArrayList<Integer>();
    }
    
    public void push(int x) {
        stack.add(x);
    }
    
    public void pop() {
        if(stack.isEmpty())
            return;
        stack.remove(stack.size() - 1);
    }
    
    public int top() {
        if(stack.isEmpty())
            return 0;
        return stack.get(stack.size() - 1);
    }
    
    public int getMin() {
         if(stack.isEmpty())
            return 0;
        int min = stack.get(0);
       for(int i = 1;i<stack.size();i++){
          if(min > stack.get(i)){
              min = stack.get(i);
          } 
       }
        return min;
    }
}
更多 LeetCode 相關資源
複習程式面試書籍
除了 LeetCode 練習外,我也入手了這本,題庫來自真正的面試,並非摘自教科書。它們反映出頂尖公司真正會出的題目,你可以藉此做好充分準備。
需要的話可以看看,寫得很仔細。
需要的話可以看看,寫得很仔細。
沒有留言:
張貼留言