LeetCode--栈和队列篇

 因为热爱所以坚持,因为热爱所以等待。熬过漫长无戏可演的日子,终于换来了人生的春天,共勉!!!

目录

1.用栈实现队列

2.用队列实现栈

3.最小栈

4.有效的括号

5.每日温度

6.下一个更大元素II


1.用栈实现队列

232. 用栈实现队列

思路:一个栈用来进队,一个栈实现出队操作

  • 进队列时stackOne添加元素,
  • 出队列时,先判断stackTwo是否为空,如果为空,则将stackOne中元素全部倒入stackTwo,然后stackTwo弹出栈顶元素(因为栈的特性stackOne中底部元素倒入stackTwo中就变成顶部元素了)
  • 取队列头元素时,增加一个字段front用来存队列头元素,当stackTwo不为空时,直接出栈顶即是队列头元素,如果stackTwo为空,则为front(记录第一个入stackOne的元素)
  • 判空即两个栈都为空则队列为空
class MyQueue {

    Stack<Integer> stackOne = new Stack<>();
    Stack<Integer> stacktwo = new Stack<>();
    int front;
    /** Initialize your data structure here. */
    public MyQueue() {

    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        if (stackOne.isEmpty()) {
            front = x;
        }
        stackOne.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        if (!empty()) {
            if (stacktwo.isEmpty()) {
                while(!stackOne.isEmpty()) {
                    stacktwo.push(stackOne.pop());
                }
            }
             return stacktwo.pop();
        }
        else 
            return -1;
    }
    
    /** Get the front element. */
    public int peek() {
        if (!empty()) {
            if (!stacktwo.isEmpty()) {
                return stacktwo.peek();
            }  
            return front;
        }
        else return -1;
        
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return stackOne.isEmpty() && stacktwo.isEmpty();
    }
}

2.用队列实现栈

225. 用队列实现栈

 思路:

class MyStack {

    Queue<Integer> queueOne = new LinkedList<>();
    Queue<Integer> queueTwo = new LinkedList<>();
    /** Initialize your data structure here. */
    public MyStack() {

    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        queueTwo.offer(x);
        while (!queueOne.isEmpty()) {
            queueTwo.offer(queueOne.poll());
        }
        Queue<Integer> temp = new LinkedList<>();
        temp = queueOne;
        queueOne = queueTwo;
        queueTwo = temp;

    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        if (!empty()) {
            if (!queueOne.isEmpty()) {
                return queueOne.poll();
            }
            return -1;
        }
        else {
            return -1;
        }
       
    }
    
    /** Get the top element. */
    public int top() {
        if (!empty()) {
            return queueOne.peek();
        }
        else
            return -1;
        
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return queueOne.isEmpty() && queueTwo.isEmpty();
    }
}

3.最小栈

155. 最小栈

思路:Node节点包含两个字段min,value;每次加元素比较栈顶元素的min和当前的value,把Math.min(stack.peek().min, value) 赋值给当前的min,插入栈中

class MinStack {

    Stack<Node> stack = new Stack<>();
    class Node {
        int min;
        int value;
        public Node(int min,int value) {
            this.min = min;
            this.value = value;
        }
    }
    /** initialize your data structure here. */
    public MinStack() {

    }
    
    public void push(int val) {
        if (stack.isEmpty()) {
            stack.push(new Node(val,val));
        }else {
            stack.push(new Node(Math.min(stack.peek().min,val),val));
        }
        
    }
    
    public void pop() {
        if (!stack.isEmpty()) {
            stack.pop();
        }
    }
    
    public int top() {
        if (!stack.isEmpty()) {
            return stack.peek().value;
        } 
        else
            return -1;
    }
    
    public int getMin() {
        if (!stack.isEmpty()) {
            return stack.peek().min;
        } 
        else
            return -1;
    }
}

4.有效的括号

20. 有效的括号


思路:如果是左括号,则存入对应的右括号,如果遇到右括号则
1.先看栈是否有元素,没有则说明只有半个括号,直接return false;
2.不空则和栈顶比较是否相同,不相同return false;
3.循环走完,看栈是否空,空则匹配成功

class Solution {
    Stack<Character> stack = new Stack<>();
    public boolean isValid(String s) {
        char[] chs = s.toCharArray();
        for (int i = 0; i < chs.length; i++) {
            if (chs[i] == '{')
                stack.push('}');
            else if (chs[i] == '[') {
                stack.push(']');
            }
            else if (chs[i] == '(') {
                stack.push(')');
            }
            else {
                if (!stack.isEmpty()) {
                    if (chs[i] == stack.peek())
                        stack.pop();
                    else
                        return false;
                }else {
                    return false;
                }         
            }
        }
        return stack.size() == 0;
    }
}

5.每日温度

739. 每日温度

 思路:维持单调栈(栈存数组下标),从栈底到栈顶依次递减,每次入栈比较当前元素与栈顶元素,如果大于栈顶,则把栈顶弹出,并且更新result数组,直到不在大于栈顶元素,或栈顶为空

class Solution {
    public int[] dailyTemperatures(int[] temperatures) {
        //维持一个单调栈
        int[] result = new int[temperatures.length];
        Deque<Integer> stack= new LinkedList<>();
        for (int i = 0; i < temperatures.length; i++) {
            int temp = temperatures[i];
            while (!stack.isEmpty() && temp > temperatures[stack.peek()]) {
                int number = stack.pop();
                result[number] = i - number; 
            }
            stack.push(i);
        }
        //后面的默认就是零,不用管了
        // while (!stack.isEmpty()) {
        //     int number = stack.pop();
        //     result[number] = 0;
        // }
        return result;
    }
}

6.下一个更大元素II

503. 下一个更大元素 II

 思路: 因为是循环数组的原因,到末尾又从头开始,所以可以遍历两遍,使用  i % len 来定位数组元素, 维持单调栈

class Solution {
    public int[] nextGreaterElements(int[] nums) {
        int len = nums.length;
        int[] result = new int[len];
        Arrays.fill(result,-1);
        Deque<Integer> stack = new LinkedList<>();
        for (int i = 0; i < 2 * len - 1; i++) {
           int num = nums[i % len]; 
            while (!stack.isEmpty() && nums[stack.peek()] < num) {
                int temp = stack.pop();
                result[temp] = num;
            } 
            if (i < len) stack.push(i);
        }
        return result;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Free的午后

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

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

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

打赏作者

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

抵扣说明:

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

余额充值