逆波兰表达式&&滑动窗口最大值(LeetCode 150&&239)

题目

150. 逆波兰表达式求值

思路

使用Character.isDigit()判断是否为数字,结果这个只能判断正数,负数就会报错!后面使用正则表达,想着匹配+-*/四个运算符,但是不会,老是报错,太多特殊字符了!就去匹配正负数! 

代码

public int evalRPN(String[] tokens) {
        Stack stack = new Stack<>();
        for (int i = 0; i < tokens.length; i++) {
            // \\-?\d+ \\-?表示-号最多出现一次 \\d+ 多位数的数字字符匹配
            if(tokens[i].matches("\\-?\\d+")){
                // 当前字符为数字 将字符转化为数字 入栈
                stack.push(Integer.valueOf(tokens[i]));
            }
            else {
                // 不为数字 则为运算符 则取出栈顶两个数字进行计算
                int temp_1 = stack.pop();
                int temp_2 = stack.pop();
                char temp = tokens[i].charAt(0);
                switch (temp){
                    case '+':
                        stack.push(temp_2 + temp_1);
                        break;
                    case '-':
                        stack.push(temp_2 - temp_1);
                        break;
                    case '*':
                        stack.push(temp_2 * temp_1);
                        break;
                    case '/':
                        stack.push(temp_2 / temp_1);
                        break;
                }

            }
        }
        return stack.pop();

题目

239. 滑动窗口最大值 

思路

主要是实现寻找滑动窗口中的最大值,代码随想录 中使用单调队列进行维护当前最大值。

代码

class My_Queue{
    Deque queue = new LinkedList<>();
    // Deque 双端队列 first和last
    // add和offer从last端添加元素
    // push、pop、peek 都是从first端操作数据
    public void Pop(int value){
        if(!queue.isEmpty() && value == queue.peek()){
            queue.pop();
        }
    }
    public void Push(int value){
        while (!queue.isEmpty() && value > queue.getLast()){
            queue.removeLast();
        }
        queue.add(value);
    }
    public int max(){
        return queue.peek();
    }
}
class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        My_Queue queue = new My_Queue();
        int[] out = new int[nums.length - k + 1];
        int flag = 0;
        for (int i = 0; i < nums.length; i++) {
            // 前面k个数 直接push到队列中
            if(i < k){
                queue.Push(nums[i]);
            }
            else {
                out[flag++] = queue.max();
                queue.Pop(nums[i-k]);
                queue.Push(nums[i]);
            }
        }
        out[flag] = queue.max();
        return out;
    }
}

你可能感兴趣的:(小菜鸡的JAVA学习,leetcode,算法,职场和发展)