【Leetcode Algorithm】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.
public class Solution {
    public int[] plusOne(int[] digits) {
        //從個位開始加1,如果產生進位直接置爲0,沒有進位則,跳出循環
        for(int i=digits.length-1;i>=0;i--){
            if((digits[i] += 1)==10){
                digits[i] = 0;
            }
            else{
                break;
            }
        }
        //如果最高位爲0,說明產生進位,則數組加長,首位爲1
        if(digits[0]==0){
            int[] newDigits = new int[digits.length+1];
            newDigits[0] = 1;
            digits = newDigits;
        }
        return digits;
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章