LeetCode155. 最小栈🌟🌟🌟🌟🌟中等

问题描述

原文链接:155. 最小栈

设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。

实现 MinStack 类:

  • MinStack() 初始化堆栈对象。
  • void push(int val) 将元素val推入堆栈。
  • void pop() 删除堆栈顶部的元素。
  • int top() 获取堆栈顶部的元素。
  • int getMin() 获取堆栈中的最小元素。

示例 1:

输入:
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

输出:
[null,null,null,null,-3,null,0,-2]

解释:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> 返回 -3.
minStack.pop();
minStack.top();      --> 返回 0.
minStack.getMin();   --> 返回 -2.

提示:

  • -231 <= val <= 231 - 1
  • pop、top 和 getMin 操作总是在非空栈上调用
  • push, pop, top, and getMin最多被调用 3 * 104 次

代码实现

Java

class MinStack {
    Stack<Integer> stack1;
    Stack<Integer> stack2;

    public MinStack() {
        stack1 = new Stack();
        stack2 = new Stack();
    }

    public void push(int val) {
        stack1.push(val);
        if(stack2.isEmpty() || stack2.peek() >= val){
            stack2.push(val);
        }
    }

    public void pop() {
        if(stack1.peek().intValue() == stack2.peek().intValue()){
            stack2.pop();
        }

        stack1.pop();
    }

    public int top() {
        return stack1.peek();
    }

    public int getMin() {
        return stack2.peek();
    }
}

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(val);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */

Python

class MinStack(object):

    def __init__(self):
        self.stack1 = []
        self.stack2 = []

    def push(self, val):
        """
        :type val: int
        :rtype: None
        """
        self.stack1.append(val)
        if not self.stack2 or self.stack2[-1] >= val:
            self.stack2.append(val)

    def pop(self):
        """
        :rtype: None
        """
        if self.stack1[-1] == self.stack2[-1]:
            self.stack2.pop()

        self.stack1.pop()

    def top(self):
        """
        :rtype: int
        """
        return self.stack1[-1]

    def getMin(self):
        """
        :rtype: int
        """
        return self.stack2[-1]

C++

class MinStack {
public:
    stack<int> stack1;
    stack<int> stack2;

    MinStack() {

    }

    void push(int val) {
        stack1.push(val);
        if(stack2.empty() || stack2.top() >= val){
            stack2.push(val);
        }
    }

    void pop() {
        if(stack1.top() == stack2.top()){
            stack2.pop();
        }

        stack1.pop();
    }

    int top() {
        return stack1.top();
    }

    int getMin() {
        return stack2.top();
    }
};

Go

type MinStack struct {
    stack1 []int
    stack2 []int
}

func Constructor() MinStack {
    return MinStack{[]int{}, []int{}}
}

func (this *MinStack) Push(val int) {
    this.stack1 = append(this.stack1, val)
    if len(this.stack2) == 0 || this.stack2[len(this.stack2)-1] >= val {
        this.stack2 = append(this.stack2, val)
    }
}

func (this *MinStack) Pop() {
    if this.stack1[len(this.stack1)-1] == this.stack2[len(this.stack2)-1] {
        this.stack2 = this.stack2[:len(this.stack2)-1]
    }

    this.stack1 = this.stack1[:len(this.stack1)-1]
}

func (this *MinStack) Top() int {
    return this.stack1[len(this.stack1)-1]
}

func (this *MinStack) GetMin() int {
    return this.stack2[len(this.stack2)-1]
}

发表回复

后才能评论

评论(6)

  • Mr.肖 永久会员 2024年4月4日 下午3:23
    class MinStack {
    
        Stack<Integer> stack1;
    
        //stack2存放当前栈里最小的元素
        Stack<Integer> stack2;
    
        public MinStack() {
            stack1 = new Stack();
            stack2 = new Stack();
        }
    
        public void push(int val) {
            if(stack1.isEmpty()){
                stack1.push(val);
                stack2.push(val);
            }else{
                stack1.push(val);
                if(val <= stack2.peek()){
                    stack2.push(val);
                }
            }
        }
    
        public void pop() {
    
            /*
            注意:stack1.pop()返回值类型是包装类Integer,比较两个包装类的内容需要用equlas方法
                不要用 == 
                如果先用 int k = stack1.pop()
                此时可以用 == (k == stack2.peek()),此时stack2.peek()返回的包装类会自动拆箱成
            */
            if( stack1.pop().equals(stack2.peek())){
                stack2.pop();
            }
        }
    
        public int top() {
            return stack1.peek();
        }
    
        public int getMin() {
            return stack2.peek();
        }
    }
    
    /**
     * Your MinStack object will be instantiated and called as such:
     * MinStack obj = new MinStack();
     * obj.push(val);
     * obj.pop();
     * int param_3 = obj.top();
     * int param_4 = obj.getMin();
     */
    
  • Yuki 永久会员 2024年2月2日 下午12:08

    打卡
    class MinStack {
    private:
    stackst;
    stack
    min_st;
    public:
    //辅助栈存放不同时期栈中的最小值
    //找最小值,用INT32_MAX初始化
    MinStack() {
    min_st.push(INT32_MAX);
    }

    void push(int val) {
        st.push(val);
        min_st.push(min(min_st.top(),val));
    }
    
    void pop() {
        st.pop();
        min_st.pop();
    }
    
    int top() {
        return st.top();
    }
    
    int getMin() {
        return min_st.top();
    }
    

    };

  • uu 永久会员 2023年9月23日 下午6:22
    // 【思路】单链表 + 栈
    // 时空复杂度太大了。。。
    // class MinStack {
    //     Stack<Integer> stack;
    //     Node ans;
    //     //内部类
    //     class Node {
    //         int val;
    //         Node next;
    
    //         public Node(int val) {
    //             this.val = val;
    //         }
    //     }
    //     public MinStack() {
    //         this.stack = new Stack();
    //         this.ans = new Node(-1);
    //     }
    
    //     public void push(int val) {
    //         stack.push(val);
    //         Node head = ans;
    //         Node newnode = new Node(val);
    //         if(ans.next == null) {
    //             ans.next = newnode;
    //         } else {
    //             while(ans.next != null) {
    //                 if(ans.next.val < newnode.val) {
    //                     ans = ans.next;
    //                 }
    //                 else {
    //                     break;
    //                 }
    //             }
    //             newnode.next = ans.next;
    //             ans.next = newnode;
    //         }
    //         ans = head;
    //     }
    
    //     public void pop() {
    //         int p = stack.pop();
    //         Node head = ans;
    
    //         while(ans.next.val != p && ans.next != null) {
    //             ans = ans.next;
    //         }
    //         ans.next = ans.next.next;
    //         ans = head;
    //     }
    
    //     public int top() {
    //         return stack.peek();
    //     }
    
    //     public int getMin() {
    //         return ans.next.val;
    //     }
    // }
    
    class MinStack {
        Stack<Integer> stack1;
        Stack<Integer> stack2;
    
        public MinStack() {
            stack1 = new Stack();
            stack2 = new Stack();
        }
    
        public void push(int val) {
            stack1.push(val);
            if(stack2.isEmpty() || stack2.peek() >= val) {
                stack2.push(val);
            }
        }
    
        // == 和equals的区别:
        // == 对于基本数据类型比较的是值,而对于引用类型比较的就是引用的地址,即两个引用是否指向同一个对象实例
        //equals 对于没有重写equals方法的引用类型的比较和==是一样的
        //只是String,包装类等重写了equals方法,所以按重写后的规则进行比较,比较的是对象指向的内容是否相等
    
        //Integer内部有一个静态变量缓存池IntegerCache,里面声明了一个Integer[]数组,范围-128——127
        //Jvm在运行时创建了一 个缓存区域并创建了一个integer的数组。
        //这个数组存储了-128至127的值。
        //stack1.peek() == stack2.peek(),如果数值在-128–127之间。比较的是数值
    
        //intValue()方法,可以拆箱,把包装类型转换成基本数据类型,这个时候比较的就是数值,
    
        public void pop() {
            if(stack1.peek().equals(stack2.peek())){
                stack2.pop();
            }
            // if(stack2.peek().intValue() == stack1.peek().intValue()) {
            //     stack2.pop();
            // }
            stack1.pop();
        }
    
        public int top() {
            return stack1.peek();
        }
    
        public int getMin() {
            return stack2.peek();
        }
    }
    
    /**
     * Your MinStack object will be instantiated and called as such:
     * MinStack obj = new MinStack();
     * obj.push(val);
     * obj.pop();
     * int param_3 = obj.top();
     * int param_4 = obj.getMin();
     */
    
    
    /**
     * Your MinStack object will be instantiated and called as such:
     * MinStack obj = new MinStack();
     * obj.push(val);
     * obj.pop();
     * int param_3 = obj.top();
     * int param_4 = obj.getMin();
     */
    
  • 泡芙 永久会员 2023年9月15日 上午11:36
    • Time:O(1),栈得插入、删除、读取都是O(1),我们定义得每个操作最多调用栈操作两次
    • Space:O(n),最坏得情况下,会连续插入n个元素,次此时两个栈占用得空间为O(n)
    class MinStack {
        Stack<Integer> stack1;
        Stack<Integer> stack2;
    
        public MinStack() {
            stack1 = new Stack<>();
            stack2 = new Stack<>();
        }
    
        public void push(int val) {
            stack1.push(val);
            if (stack2.isEmpty() || val <= stack2.peek()) {
                stack2.push(val);
            }
        }
    
        public void pop() {
            // if (stack1.peek().intValue() == stack2.peek().intValue()) {
            //     stack2.pop();
            // }
            if (stack1.peek().equals(stack2.peek())) {
                stack2.pop();
            }
            stack1.pop();
        }
    
        public int top() {
            return stack1.peek();
        }
    
        public int getMin() {
            return stack2.peek();
        }
    }
    
  • 阿尚 普通 2023年8月19日 下午5:15
    class MinStack {
        Stack<Integer> valStack;
        Stack<Integer> minStack;//栈顶即为最小元素
        public MinStack() {
            valStack = new Stack<>();
            minStack = new Stack<>();
        }
    
        public void push(int val) {
            if(valStack.isEmpty()){
                minStack.push(val);
            }else{
                if(val < minStack.peek()){
                    minStack.push(val);
                }else{
                    minStack.push(minStack.peek());
                }
            }
            valStack.push(val);
        }
    
        public void pop() {
            valStack.pop();
            minStack.pop();
        }
    
        public int top() {
            return valStack.peek();
        }
    
        public int getMin() {
            return minStack.peek();
        }
    }
    
  • 帅气的冬瓜 普通 2023年6月30日 下午2:13

    打卡

如果您已经成功付款但是网站没有弹出成功提示,请联系站长提供付款信息为您处理