剑指offer---------栈篇

面试题30.包含min函数的栈(155)

原题

在这里插入图片描述

题解

方法一:辅助栈和数据栈同步(剑指offer)

在这里插入图片描述

//java
class MinStack {
    Stack<Integer> A, B;  //B是辅助栈

    /** initialize your data structure here. */
    public MinStack() {
        A = new Stack<>();
        B = new Stack<>();
    }
    
    public void push(int x) {
        A.push(x);
        if(B.empty() || x <= B.peek()){
            B.push(x);
        }else{
            B.push(B.peek());
        }
    }
    
    public void pop() {
        if(!A.empty()){
            A.pop();
            B.pop();
        }
    }
    
    public int top() {
        return A.peek();
    }
    
    public int min() {
        return B.peek();
    }
}
//java 别人家的代码   考虑了异常
import java.util.Stack;

public class MinStack {

    // 数据栈
    private Stack<Integer> data;
    // 辅助栈
    private Stack<Integer> helper;

    /**
     * initialize your data structure here.
     */
    public MinStack() {
        data = new Stack<>();
        helper = new Stack<>();
    }

    // 思路 1:数据栈和辅助栈在任何时候都同步

    public void push(int x) {
        // 数据栈和辅助栈一定会增加元素
        data.add(x);
        if (helper.isEmpty() || helper.peek() >= x) {
            helper.add(x);
        } else {
            helper.add(helper.peek());
        }
    }

    public void pop() {
        // 两个栈都得 pop
        if (!data.isEmpty()) {
            helper.pop();
            data.pop();
        }
    }

    public int top() {
        if(!data.isEmpty()){
            return data.peek();
        }
        throw new RuntimeException("栈中元素为空,此操作非法");
    }

    public int getMin() {
        if(!helper.isEmpty()){
            return helper.peek();
        }
        throw new RuntimeException("栈中元素为空,此操作非法");
    }
}

作者:liweiwei1419
链接:https://leetcode-cn.com/problems/min-stack/solution/shi-yong-fu-zhu-zhan-tong-bu-he-bu-tong-bu-python-/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

方法二:辅助栈和数据栈不同步

在这里插入图片描述

//java
class MinStack {
    Stack<Integer> A, B;  //B是辅助栈

    /** initialize your data structure here. */
    public MinStack() {
        A = new Stack<>();
        B = new Stack<>();
    }
    
    public void push(int x) {
        A.push(x);
        if(B.empty() || x <= B.peek()){   //等号一定要考虑进来
            B.push(x);
        }
    }
    
    public void pop() {
        if(A.peek().equals(B.peek())){
        //if(A.peek() == B.peek()){   //这样写不对
        //Java 代码中,由于 Stack 中存储的是 int 的包装类 Integer ,因此需要使用 equals() 代替 == 来比较值是否相等
            B.pop();
        }
        if(!A.empty()){
            A.pop();
        }
    }

	/*  上述的简化写法
    public void pop() {
        if(A.pop().equals(B.peek()))
            B.pop();
    }
    */


	/* 用==比较的话,必须先完成自动拆箱
	public void pop() {
        if (!A.isEmpty()) {
            // 注意:声明成 int 类型,这里完成了自动拆箱,从 Integer 转成了 int,因此下面的比较可以使用 "==" 运算符
            // 参考资料:https://www.cnblogs.com/GuoYaxiang/p/6931264.html
            // 如果把 top 变量声明成 Integer 类型,下面的比较就得使用 equals 方法
            int top = A.pop();
            if(top == B.peek()){
                B.pop();
            }
        }
    }
	*/  
	  
    public int top() {
        return A.peek();
    }
    
    public int min() {
        return B.peek();
    }
}

//Java 别人家的代码 考虑了异常
import java.util.Stack;

public class MinStack {

    // 数据栈
    private Stack<Integer> data;
    // 辅助栈
    private Stack<Integer> helper;

    /**
     * initialize your data structure here.
     */
    public MinStack() {
        data = new Stack<>();
        helper = new Stack<>();
    }

    // 思路 2:辅助栈和数据栈不同步
    // 关键 1:辅助栈的元素空的时候,必须放入新进来的数
    // 关键 2:新来的数小于或者等于辅助栈栈顶元素的时候,才放入(特别注意这里等于要考虑进去)
    // 关键 3:出栈的时候,辅助栈的栈顶元素等于数据栈的栈顶元素,才出栈,即"出栈保持同步"就可以了

    public void push(int x) {
        // 辅助栈在必要的时候才增加
        data.add(x);
        // 关键 1 和 关键 2
        if (helper.isEmpty() || helper.peek() >= x) {
            helper.add(x);
        }
    }

    public void pop() {
        // 关键 3:data 一定得 pop()
        if (!data.isEmpty()) {
            // 注意:声明成 int 类型,这里完成了自动拆箱,从 Integer 转成了 int,因此下面的比较可以使用 "==" 运算符
            // 参考资料:https://www.cnblogs.com/GuoYaxiang/p/6931264.html
            // 如果把 top 变量声明成 Integer 类型,下面的比较就得使用 equals 方法
            int top = data.pop();
            if(top == helper.peek()){
                helper.pop();
            }
        }
    }

    public int top() {
        if(!data.isEmpty()){
            return data.peek();
        }
        throw new RuntimeException("栈中元素为空,此操作非法");
    }

    public int getMin() {
        if(!helper.isEmpty()){
            return helper.peek();
        }
        throw new RuntimeException("栈中元素为空,此操作非法");
    }

}

作者:liweiwei1419
链接:https://leetcode-cn.com/problems/min-stack/solution/shi-yong-fu-zhu-zhan-tong-bu-he-bu-tong-bu-python-/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

面试题31.栈的压入、弹出序列(946.验证栈序列)

题目

在这里插入图片描述

安安解法:代码有些繁琐

//java 安安 2020.4.24
class Solution {
    public boolean validateStackSequences(int[] pushed, int[] popped) {
        Stack<Integer> stack = new Stack<>();
        int i = 0, j = 0;
        while(j < popped.length){   //结束的条件是:popped数组所有数值都满足条件
            //System.out.println("i=" + i + ", j=" + j);
            //pushed数组中的元素还没有遍历完,需要综合考虑pushed数组中的值和stack
            if(i < pushed.length){   
                if(pushed[i] != popped[j]){
                    if(!stack.empty() && stack.peek().equals(popped[j])){
                        stack.pop();                       
                        j++;
                    }else{
                        stack.push(pushed[i]);                       
                        i++;
                    }               
                }else{
                    j++;
                    i++;
                }
            }else{    //pushed数组中的元素已经遍历完,只需要考虑stack中的数值即可  
                int topE =  stack.peek();
                if(!stack.empty() && topE == popped[j]){
                    stack.pop();                  
                    j++;
                }else{
                    return false;
                }
            }
        }
        return true;  //popped数组所有数值都满足条件
    }
} 

官解:辅助栈

在这里插入图片描述

在这里插入图片描述

class Solution {
    public boolean validateStackSequences(int[] pushed, int[] popped) {
        int N = pushed.length;
        Stack<Integer> stack = new Stack();

        int j = 0;
        for (int x: pushed) {
            stack.push(x);
            while (!stack.isEmpty() && j < N && stack.peek() == popped[j]) {
                stack.pop();
                j++;
            }
        }

        return j == N;
    }
}

作者:LeetCode
链接:https://leetcode-cn.com/problems/validate-stack-sequences/solution/yan-zheng-zhan-xu-lie-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

安安csdn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值