Skip to content

Instantly share code, notes, and snippets.

@charlieInDen
Created January 19, 2021 10:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save charlieInDen/277bb4a31cf232677183f31ad12839e4 to your computer and use it in GitHub Desktop.
Save charlieInDen/277bb4a31cf232677183f31ad12839e4 to your computer and use it in GitHub Desktop.
class MinStack {
private var arr: [(Int, Int)]
/** initialize your data structure here. */
init() {
arr = [(Int,Int)]()
}
func push(_ x: Int) {
let prevMax = peek().1
arr.append((x, min(prevMax,x)))
}
func pop() {
guard arr.count > 0 else {
return
}
arr.removeLast()
}
func top() -> Int {
return peek().0
}
func getMin() -> Int {
return peek().1
}
private func peek() -> (Int,Int){
guard arr.count > 0 else {
return (-1, Int.max)
}
return arr[arr.count - 1]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment