Created
January 19, 2021 10:43
-
-
Save charlieInDen/73dcbc20793b09af5796447194e0c704 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MaxStack { | |
// two stack | |
// one regular stack | |
// one max stack, keep track latest max | |
var stack: [Int] = [] | |
var maxStack: [Int] = [] | |
init() { | |
} | |
func push(_ x: Int) { | |
stack.append(x) | |
maxStack.append(maxStack.isEmpty ? x : max(maxStack.last!, x)) | |
} | |
func pop() -> Int { | |
maxStack.removeLast() | |
return stack.removeLast() | |
} | |
func top() -> Int { | |
return stack.last! | |
} | |
func peekMax() -> Int { | |
return maxStack.last! | |
} | |
func popMax() -> Int { | |
let max = maxStack.last! | |
var tmp: [Int] = [] | |
while let lastItem = stack.popLast() { | |
maxStack.removeLast() | |
if lastItem == max { | |
print("removed:",lastItem) | |
break | |
} else { | |
tmp.append(lastItem) | |
} | |
} | |
while let lastItem = tmp.popLast() { | |
self.push(lastItem) | |
} | |
return max | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment