Min function comprising a stack (stack find the smallest value)

problem

Stack data structure definition, implement this type can be a min function smallest elements contained in the stack (should the time complexity O (1)).
Note: to ensure that the test is not when the stack is empty, calls on the stack pop () or min () or top () method.

analysis

A thought

Method 1 @:
@ define a minimum value min of additional storage stack, but each insertion, remove the stack needs to maintain a minimum value when the minimum

Ideas two

@ Method 2:
// define a two stack
// Stack A: storing data
// stack B: 存放栈A中当前元素的最小值, when the top element in the stack A stack, it is determined
// When all elements in the stack into the stack A when the same is determined, if the push element is smaller than the top element of the stack B, the element is pushed onto the stack page B
Here Insert Picture Description

Code

package DlinkedList;

import ATree.Problem6;

import java.util.ArrayList;
import java.util.Stack;

/**
 * @Author Zhou  jian
 * @Date 2020 ${month}  2020/3/21 0021  16:09
 * 定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数
 * (时间复杂度应为O(1))。
    注意:保证测试中不会当栈为空的时候,对栈调用pop()或者min()或者top()方法。
 */
public class Problem7 {

    //方法1:
    //可以定义一个额外的min保存栈中的最小值,但是每次插入,取出栈中最小值的时候都需要维护这个最小值

    //方法2:
    //可以定义一个两个栈
    //栈A:存放数据
    //栈B:存放栈A中当前元素的最小值,当栈A中的栈顶元素出栈时,则判断
                        //     当栈A中有元素进栈的时候,同样判断,若入栈的元素小于栈B的栈顶元素,则将该元素页压入栈B



    Stack<Integer> A=new Stack<>();
    Stack<Integer> B=new Stack<>();

    public void push(int node) {
        //若栈为空
        if(A.size()==0){
            A.push(node);
            B.push(node);
        }else{
            //假如压栈的元素小于栈B顶的元素则页压入到栈B中
            A.push(node);
            if(node<B.peek()){
                B.push(node);
            }

        }

    }

    public void pop() {
        //假如当前出栈的元素就是最小元素,则页应从栈B中出栈
        if(top()==B.peek()){
            B.pop();
        }
        A.pop();
    }

    //查看栈顶元素
    public int top() {
        return A.peek();
    }

    public int min() {
        //返回栈B的栈顶元素即可
        return B.peek();
    }

    public static void main(String[] args) {
        Problem7 problem7 = new Problem7();
        problem7.push(20);
        problem7.push(12);
        problem7.push(15);
        problem7.push(2);
        problem7.push(33);
        problem7.pop();
        problem7.pop();
        problem7.pop();

        System.out.println(problem7.min());




    }
}


He published 198 original articles · won praise 20 · views 20000 +

Guess you like

Origin blog.csdn.net/ZHOUJIAN_TANK/article/details/105012621