From ae0d52cf9c85123b2637492fe8575ea2e29b90b9 Mon Sep 17 00:00:00 2001 From: yanglbme <szuyanglb@outlook.com> Date: Wed, 7 Feb 2024 21:23:54 +0800 Subject: [PATCH] feat: update solution to lcci problem: No.03.02 --- lcci/03.02.Min Stack/README_EN.md | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/lcci/03.02.Min Stack/README_EN.md b/lcci/03.02.Min Stack/README_EN.md index dfa3b78c33932..053d35e2e8b9e 100644 --- a/lcci/03.02.Min Stack/README_EN.md +++ b/lcci/03.02.Min Stack/README_EN.md @@ -28,7 +28,16 @@ minStack.getMin(); --> return -2.</pre> ## Solutions -### Solution 1 +### Solution 1: Double Stack + +We use two stacks to implement this, where `stk1` is used to store data, and `stk2` is used to store the current minimum value in the stack. Initially, `stk2` stores a very large value. + +- When we push an element `x` into the stack, we push `x` into `stk1`, and push `min(x, stk2[-1])` into `stk2`. +- When we pop an element from the stack, we pop the top elements of both `stk1` and `stk2`. +- When we want to get the top element in the current stack, we just need to return the top element of `stk1`. +- When we want to get the minimum value in the current stack, we just need to return the top element of `stk2`. + +For each operation, the time complexity is $O(1)$, and the space complexity is $O(n)$. <!-- tabs:start -->