{ "cells": [ { "cell_type": "markdown", "source": [ "Design a stack that supports push, pop, top, and retrieving the minimum\n", "element in constant time.\n", "\n", " * push(x) -- Push element x onto stack.\n", " * pop() -- Removes the element on top of the stack.\n", " * top() -- Get the top element.\n", " * getMin() -- Retrieve the minimum element in the stack.\n", "\n", "\n", "\n", "**Example 1:**\n", "\n", "\n", "\n", " **Input**\n", " [\"MinStack\",\"push\",\"push\",\"push\",\"getMin\",\"pop\",\"top\",\"getMin\"]\n", " [[],[-2],[0],[-3],[],[],[],[]]\n", "\n", " **Output**\n", " [null,null,null,null,-3,null,0,-2]\n", "\n", " **Explanation**\n", " MinStack minStack = new MinStack();\n", " minStack.push(-2);\n", " minStack.push(0);\n", " minStack.push(-3);\n", " minStack.getMin(); // return -3\n", " minStack.pop();\n", " minStack.top(); // return 0\n", " minStack.getMin(); // return -2\n", "\n", "\n", "\n", "\n", "**Constraints:**\n", "\n", " * Methods `pop`, `top` and `getMin` operations will always be called on **non-empty** stacks." ], "metadata": {} }, { "outputs": [ { "output_type": "execute_result", "data": { "text/plain": "get_min (generic function with 1 method)" }, "metadata": {}, "execution_count": 1 } ], "cell_type": "code", "source": [ "# @lc code=start\n", "using LeetCode\n", "Base.@kwdef struct MinStack{V<:Number}\n", " nums::Vector{V} = Int[]\n", " min_nums::Vector{V} = Int[]\n", "end\n", "\n", "function Base.push!(stack::MinStack, val::Int)::Nothing\n", " Base.push!(stack.nums, val)\n", " if isempty(stack.min_nums) || val <= stack.min_nums[end]\n", " Base.push!(stack.min_nums, val)\n", " end\n", " return nothing\n", "end\n", "\n", "function Base.pop!(stack::MinStack)::Nothing\n", " if Base.pop!(stack.nums) == stack.min_nums[end]\n", " Base.pop!(stack.min_nums)\n", " end\n", " return nothing\n", "end\n", "\n", "top(stack::MinStack)::Int = stack.nums[end]\n", "\n", "get_min(stack::MinStack)::Int = stack.min_nums[end]\n", "# @lc code=end" ], "metadata": {}, "execution_count": 1 }, { "cell_type": "markdown", "source": [ "---\n", "\n", "*This notebook was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*" ], "metadata": {} } ], "nbformat_minor": 3, "metadata": { "language_info": { "file_extension": ".jl", "mimetype": "application/julia", "name": "julia", "version": "1.10.1" }, "kernelspec": { "name": "julia-1.10", "display_name": "Julia 1.10.1", "language": "julia" } }, "nbformat": 4 }