LeetCode – 155. Min Stack

題目連結: https://leetcode.com/problems/min-stack/

要提出來的問題

Q: Is any two elements with the same value? Ans: No
Q: Specific data structure for implementing stack? Ans: array
Q: Is there any time complexity or space complexity constraints for each function?

Ans:
Push O(1)
pop O(1)
top O(1)
getMin O(1)
Q: What should we return for func top() if the stack is empty? Ans: -1
Q: Is there any size constraint for stack? Ans: No

class MinStack {
    struct MinInt {
        var min: Int
        var val: Int
    }
    var arr: [MinInt]
    init() {
        arr = [MinInt]()
    }
    
    func push(_ val: Int) {
        if arr.count > 0 {
            var curMin = val < getMin() ? val : getMin()
            arr.append(MinInt(min: curMin, val: val))
        } else {
            arr.append(MinInt(min: val, val: val))
        }
    }
    
    func pop() {
        _ = arr.removeLast()
    }
    
    func top() -> Int {
        return arr.last?.val ?? -1
    }
    
    func getMin() -> Int {
        return arr.last?.min ?? -1
    }
}

Ref:

https://leetcode.com/problems/min-stack/discuss/265256/Swift

https://leetcode.com/problems/min-stack/discuss/963777/Swift-Tuple