Sword refers to offer to brush questions-GZ20-stack containing min function

Topic description
Define the data structure of the stack. Please implement a min function in this type that can get the smallest element contained in the stack (time complexity should be O(1)).
Problem-solving idea:
Seeing this problem, we may at first think, add a member variable to store the smallest element, and if the pushed element is smaller than the current smallest element each time the stack is pushed, the smallest element
will be updated. But this will There is a question, if the smallest element is popped up, how to get the next smallest element? It can be found from the analysis that just adding a member variable to store the smallest element is not enough. We need to get the next smallest element after the smallest element is popped up. After the next
smallest element is popped
, you can still get the next smallest element . Therefore, it is more appropriate to use another stack to store these elements. We call it the smallest element stack. Each time the stack is pushed, if you press The stack element is smaller than the current smallest element, just push this element into the smallest element stack, and the original smallest element becomes the second smallest element. Similarly, when popping the stack, if the popped element is equal to the top element of the smallest element stack , Just pop the top of the stack of the smallest element.

import java.util.Stack;

public class Solution {
    
    
    /**
     解题思路:
         创建一个用来保存最小元素的栈stackMin。
     stack要入栈时:入栈元素node每次都和stackMin中的栈顶元素比较,如果比stackMin中的最小元素小
            那么就将node入stackMin栈。否则只入stack栈。
     stack要出栈时:每次都和stackMin栈中的栈顶元素比较,如果相等,那么说明stack中的最小元素出栈了,
            那么,stackMin中的栈顶元素也要出栈。这样就保证了stackMin中的栈顶元素一定是stack中的
            最小元素
    */
    private Stack<Integer> stack = new Stack<>();
    private Stack<Integer> stackMin = new Stack();
    public void push(int node) {
    
    
        stack.push(node);
        if(stackMin.empty()){
    
    //如果最小元素栈为空就将这个元素添加进去
            stackMin.push(node);
        } else if(node < stackMin.peek()){
    
    //如果当前要入栈的元素小于stackMin的栈顶元素,那么就push
            stackMin.push(node);
        }
    }
    
    public void pop() {
    
    
        if(stack.peek().equals(stackMin.peek())){
    
    
            stackMin.pop();
        }
        stack.pop();
    }
    
    public int top() {
    
    
        return stack.peek();//查看栈顶元素
    }
    
    public int min() {
    
    
        return stackMin.peek();
    }
}

Guess you like

Origin blog.csdn.net/weixin_42118981/article/details/113065005