2021年6月8号,力扣刷题记录---Java---栈与队列

栈与队列

232. 用栈实现队列

题目地址

题目描述

请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):

实现 MyQueue 类:

  • void push(int x) 将元素 x 推到队列的末尾

  • int pop() 从队列的开头移除并返回元素

  • int peek() 返回队列开头的元素

  • boolean empty() 如果队列为空,返回 true ;否则,返回 false

  • 你只能使用标准的栈操作 —— 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。

  • 你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。

示例 1:
输入:
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 1, 1, false]

解释:
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false

思路

栈实现队列,首先知道栈的特点是先入后出,队列特点是先入先出。目标:使用两个栈实现一个队列。
使用两个栈,一个栈inStack专门用来接收数据,另一个栈outStack专门用来pop,peek处理。inStack中接收到的数据,需要在outStack中进行倒置。这一功能使用函数in2out实现。

代码及注释

class MyQueue {
    Deque<Integer> inStack;
    Deque<Integer> outStack;

    /** Initialize your data structure here. */
    public MyQueue() {
        inStack = new LinkedList<Integer>();
        outStack = new LinkedList<Integer>();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        inStack.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        if (!outStack.isEmpty()) {
            return outStack.pop();
        } else {
            in2out();
        }
        return outStack.pop();
    }
    
    /** Get the front element. */
    public int peek() {
        if (!outStack.isEmpty()) {
            return outStack.peek();
        } else {
            in2out();
        }
        return outStack.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return outStack.isEmpty()&inStack.isEmpty();
    }

    public void in2out() {
        while (!inStack.isEmpty()){
            outStack.push(inStack.pop());
        }
    }
}

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * boolean param_4 = obj.empty();
 */

225. 用队列实现栈

题目地址

题目描述

请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通队列的全部四种操作(push、top、pop 和 empty)。

实现 MyStack 类:

  • void push(int x) 将元素 x 压入栈顶。

  • int pop() 移除并返回栈顶元素。

  • int top() 返回栈顶元素。

  • boolean empty() 如果栈是空的,返回 true ;否则,返回 false

  • 你只能使用队列的基本操作 —— 也就是 push to back、peek/pop from front、size 和 is empty 这些操作。

  • 你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。

示例 1:

[输入:
["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 2, 2, false]

解释:
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // 返回 2
myStack.pop(); // 返回 2
myStack.empty(); // 返回 False

思路

队列实现栈的功能。上题知道队列:先入先出;栈:后入先出。两个队列(先入先出的函数)实现一个栈(后入先出的函数)。

在输入队列inQue中接收数据,outQue中用于peek和pop功能实现。可以先在inQue中即进行输入数据的翻转,重新排列使其后入的数据放置到先出的位置,然后将inQue赋予outQue。

代码及注释

class MyStack {
    Queue<Integer> inQueue;
    Queue<Integer> outQueue;

    /** Initialize your data structure here. */
    public MyStack() {
        inQueue = new LinkedList<Integer>();
        outQueue = new LinkedList<Integer>();
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        inQueue.offer(x);
        while (!outQueue.isEmpty()) {
            inQueue.offer(outQueue.poll());
        }
        Queue<Integer> temp = inQueue;
        inQueue = outQueue;
        outQueue = temp;
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        return outQueue.poll();
    }
    
    /** Get the top element. */
    public int top() {
        return outQueue.peek();
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return outQueue.isEmpty();
    }
}

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * boolean param_4 = obj.empty();
 */

20. 有效的括号

题目地址

题目描述

给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串 s ,判断字符串是否有效。

有效字符串需满足:

  • 左括号必须用相同类型的右括号闭合。
  • 左括号必须以正确的顺序闭合。
示例 1:

输入:s = "()"
输出:true
示例 2:

输入:s = "(]"
输出:false
示例 3:
输入:s = "([)]"
输出:false
示例 4:
输入:s = "{[]}"
输出:true

思路

为了判断括号的先后顺序,与搭配情况,可以按照怎样才是正确的结果。可以采用栈来进行处理。
方法一:

  • 当出现’)’ ,’]’,’}‘右括号的时候,应该考虑栈stack中最顶层应该是’(’ ,’[’,’{’,否则返回false。
    最顶层不是左括号的时候,可能有以下两种情况。1,栈stack为空,则直接返回false; 2、栈stack不是空,但也不是与其相对应的右括号。这种情况则将该括号放入栈中
    方法二:
  • 使用Map放置对应的关系。

代码及注释

方法一:

class Solution {
    public boolean isValid(String s) {
        Deque<Character> stack = new LinkedList<Character>();
        char[] arr = s.toCharArray();

        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == ')') {
                if (stack.isEmpty()) {
                    return false;
                } else if (stack.pop() == '(') {
                    continue;
                } else {
                    stack.push(arr[i]);
                }
            } else if (arr[i] == '}') {
                if (stack.isEmpty()) {
                    return false;
                } else if (stack.pop() == '{') {
                    continue;
                } else {
                    stack.push(arr[i]);
                }
            } else if (arr[i] == ']') {
                if (stack.isEmpty()) {
                    return false;
                } else if (stack.pop() == '[') {
                    // stack.pop();
                    continue;
                } else {
                    stack.push(arr[i]);
                }
            } else {
                stack.push(arr[i]);
            }
        }
       
        return stack.isEmpty();
    }
}

方法二:

class Solution {
    public boolean isValid(String s) {
        Map<Character, Character> pairs = new HashMap<>() {{
            put(')', '(');
            put(']', '[');
            put('}', '{');
        }};

        Deque<Character> stack = new LinkedList<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (pairs.containsKey(c)) {
                if (stack.isEmpty() || pairs.get(c) != stack.peek()) {
                    return false;
                }
                stack.pop();
            } else {
                stack.push(c);
            }
        }
        return stack.isEmpty();
    }
}

1047. 删除字符串中的所有相邻重复项

题目地址

题目描述

给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。

在 S 上反复执行重复项删除操作,直到无法继续删除。

在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。

示例 1:
输入:"abbaca"
输出:"ca"
解释:
例如,在 "abbaca" 中,我们可以删除 "bb" 由于两字母相邻且相同,这是此时唯一可以执行删除操作的重复项。之后我们得到字符串 "aaca",其中又只有 "aa" 可以执行重复项删除操作,所以最后的字符串为 "ca"

思路

将字符串中相邻的两个元素进行删除操作,可以使用StringBuffer来存储结果。
方法一:使用栈stack来比较即将存入的元素,与栈中的第一个元素进行比较
方法二:直接使用字符数组来存储已经匹配好的字符串,该操作无须删除元素,直接根据下标来进行操作。

代码及注释

方法一:

class Solution {
    public String removeDuplicates(String s) {
        Stack<Character> stack = new Stack<>();
        
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            //判断栈为空或者两个相邻字符不一样,则直接添加
            if (stack.isEmpty() || c != stack.peek()) {
                stack.push(c);
            } else {
                stack.pop();
            }
        }

        StringBuilder str = new StringBuilder();
        Deque<Character> temp = new LinkedList<>();
        // while (!stack.isEmpty()) {
        //     temp.push(stack.pop());
        // }
        // while (!temp.isEmpty()) {
        //     str.append(temp.pop());
        // }
        for (Character c : stack) {
            str.append(c);
        }
        
        return str.toString();
    }
}

方法二:

class Solution {
    public String removeDuplicates(String s) {
        char[] sArr = s.toCharArray();
        int top = -1;

        for (int i = 0; i < sArr.length; i++) {
            if (top == -1 || sArr[top] != sArr[i]) {
                sArr[++top] = sArr[i];
            } else {
                top--;
            }
        }

        return String.valueOf(sArr, 0, top + 1);
    }
}

150. 逆波兰表达式求值

题目地址

题目描述

根据 逆波兰表示法,求表达式的值。

有效的算符包括 +、-、*、/ 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。

说明:

  • 整数除法只保留整数部分。
  • 给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。
示例 1:
输入:tokens = ["2","1","+","3","*"]
输出:9
解释:该算式转化为常见的中缀算术表达式为:((2 + 1) * 3) = 9
示例 2:
输入:tokens = ["4","13","5","/","+"]
输出:6
解释:该算式转化为常见的中缀算术表达式为:(4 + (13 / 5)) = 6
示例 3:
输入:tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
输出:22
解释:
该算式转化为常见的中缀算术表达式为:
  ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22

思路

  • 对字符串进行字符判断,判断该字符串是否是数字,使用isNumber实现
  • 对于数字,则存入栈中。如果是运算符,则将数字剔出,参与运算,并将运算结果输入到栈中。
    注意:
  • 将字符串数字转换成Integer形式存入栈,函数:Integer.parseInt(token)

代码及注释

class Solution {
    public int evalRPN(String[] tokens) {
        //首先判断该String类型是不是运算符
        //不是运算符的话,将数字push到栈中
        //若是运算符,则取出栈中的两个数字进行运算符处理
        Stack<Integer> stack = new Stack<Integer>();

        for (int i = 0; i < tokens.length; i++) {
            if (isNumber(tokens[i])) {
                stack.push(Integer.parseInt(tokens[i]));
            } else {
                int num1 = stack.pop();
                int num2 = stack.pop();
                switch(tokens[i]) {
                    case "+": stack.push(num2 + num1); break;
                    case "-": stack.push(num2 - num1); break;
                    case "*": stack.push(num2 * num1); break;
                    case "/": stack.push(num2 / num1); break;
                    default :
                        break;
                }
            }
        }
        return stack.pop();
    }
    public boolean isNumber(String token) {
        return !(token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/"));
    }
}

239. 滑动窗口最大值

题目地址

题目描述

给你一个整数数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。

返回滑动窗口中的最大值。

示例 1:
输入:nums = [1,3,-1,-3,5,3,6,7], k = 3
输出:[3,3,5,5,6,7]
解释:
滑动窗口的位置                最大值
---------------               -----
[1  3  -1] -3  5  3  6  7       3
 1 [3  -1  -3] 5  3  6  7       3
 1  3 [-1  -3  5] 3  6  7       5
 1  3  -1 [-3  5  3] 6  7       5
 1  3  -1  -3 [5  3  6] 7       6
 1  3  -1  -3  5 [3  6  7]      7
示例 2:
输入:nums = [1], k = 1
输出:[1]
示例 3:
输入:nums = [1,-1], k = 1
输出:[1,-1]
示例 4:
输入:nums = [9,11], k = 2
输出:[11]
示例 5:
输入:nums = [4,-2], k = 2
输出:[4]

思路

本题可以通过存储数组下标进行处理,将k范围内的最大值放入队列的头部,不断滑动窗口,pop

代码及注释

class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        if (nums == null || nums.length < 2)
            return nums;

        //双向队列(实际上采用单向递减栈) 保存当前窗口最大值的数组位置 
        //保证队列中数组位置的数值按从大到小排序
        LinkedList<Integer> queue = new LinkedList();
        //结果存放数组
        int[] ans = new int[nums.length - k + 1];

        for (int i = 0; i < nums.length; i++){
            //保证栈从大到小排列,如果将要填充的数字大于前一个数字,则依次弹出,直至满足要求
            while (!queue.isEmpty() && nums[queue.peekLast()] <= nums[i]){
                queue.pollLast();
            }
            //添加当前值的下标
            queue.addLast(i);
            //判断当前栈中的首数字下标是否还在窗口之中
            if (i - queue.peek() >= k){
                queue.poll();
            }
            //下面语句我难以理解,于是改成上面的语句,理解相对直白一些
            // if(queue.peek() <= i-k){
            //     queue.poll();   
            // } 
            //窗口为k时,保存当前窗口中的最大值
            if (i + 1 >= k ){
                ans[i-k+1] = nums[queue.peek()];
            }
        }
        return ans;
    }
}

347. 前 K 个高频元素

题目地址

题目描述

给你一个整数数组 nums 和一个整数 k ,请你返回其中出现频率前 k 高的元素。你可以按任意顺序返回答案。

示例 1:
输入: nums = [1,1,1,2,2,3], k = 2
输出: [1,2]
示例 2:
输入: nums = [1], k = 1
输出: [1]

思路

本题可以通过Map获取元素和各个元素出现的次数。
然后按照频次将各个元素进行排序
最后找出频次出现较高的k个元素

代码及注释

class Solution {
    public int[] topKFrequent(int[] nums, int k) {
        //使用Map存储各个元素,及其出现的次数
        Map<Integer, Integer> map = new HashMap<>();
        for (int num : nums)
            map.put(num, map.getOrDefault(num, 0) + 1);
        
        //构造小根堆(即最小堆),用以保存前k个出现频率最高的元素
        PriorityQueue<Integer> queue = new PriorityQueue<>(new Comparator<Integer>(){
            // 这里是用了 Java 的匿名内部类来实现 Comparator 接口中的 compare 方法,
            // 目的是让 minHeap 根据数字出现的频率进行升序排序(因为是小根堆,所以是升序)
            @Override
            public int compare(Integer a, Integer b){
                return map.get(a) - map.get(b);
            }
        });

        for (Integer key : map.keySet()) {
            if (queue.size() < k){
                queue.add(key);
            } else if (map.get(key) > map.get(queue.peek())) {
                queue.poll();
                queue.add(key);
            }
        }

        int[] ans = new int[k];
        int Index = 0;

        while (!queue.isEmpty()) {
            ans[Index++] = queue.peek();
            queue.poll();
        }

        return ans;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值