Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How does LeetCode implement a stack containing min functions

Shulou Source: shulou.com Published: 2022-06-01 13:03:49 10月03日 Update

This article mainly introduces how to implement the stack containing min function by LeetCode. It is very detailed and has certain reference value. Friends who are interested must finish reading it.

1. Brief introduction of the problem.

To define the data structure of the stack, implement a min function in this type that can get the smallest elements of the stack. In this stack, the time complexity of calling min, push, and pop is O (1).

2, example

Example:

MinStack minStack = new MinStack (); minStack.push (- 2); minStack.push (0); minStack.push (- 3); minStack.min ();-- > return-3.minStack.pop (); minStack.top ();-- > return 0.minStack.min ();-- > return-2.

Tip:

The total number of calls to each function does not exceed 20000

3. The problem solving idea is solved by using the existing Stack provided by java.

4, problem solving procedure

Import java.util.Iterator;import java.util.Stack

Public class MinStack {static Stack stack = new Stack ()

Public static void main (String [] args) {MinStack minStack = new MinStack (); minStack.push (- 2); minStack.push (0); minStack.push (- 3); System.out.println ("stack =" + stack); int min = minStack.min (); System.out.println ("min =" + min); int pop = minStack.pop () System.out.println ("pop =" + pop); int top = minStack.top (); System.out.println ("top =" + top); int min1 = minStack.min (); System.out.println ("min1 =" + min1);}

Public MinStack () {

}

Public void push (int x) {stack.push (x);}

Public int pop () {Integer pop = stack.pop (); return pop;}

Public int top () {return stack.peek ();}

Public int min () {Integer min = stack.peek (); Iterator iterator = stack.iterator (); while (iterator.hasNext ()) {Integer val = iterator.next (); if (min > val) {min = val;}} return min;}}

5. Picture version of the problem solving program.

These are all the contents of the article "how LeetCode implements the stack that contains min functions". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Tags: Functions problem solutions content examples programs articles complexity minimization value elements interests pictures complexity guys buddies ideas data data structures time more Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft Shulou Technology vpn Xiaomi Redmi