力扣算法JS LC [150. 逆波兰表达式求值] LC [239. 滑动窗口最大值]

138 阅读2分钟

LC 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

解题思路:在映射表中存储运算符及其对应的运算规则,然后遍历 tokens,没遇到跟映射表中一样的值时,直接放进栈中。有遇到时,就将栈中最后两个值拿出来,按照对应的运算规则进行运算,然后再放进栈中

代码:

var evalRPN = function(tokens) {
    const stack = [];
    const map = new Map([
        ["+", (a,b) => a * 1 + b * 1], 
        ["-", (a,b) => b - a], 
        ["*", (a,b) => a * b], 
        ["/", (a,b) => (b / a) > 0 ? Math.floor(b / a) : Math.ceil(b / a)]
        ]);
    for(const i of tokens) {
        if(map.has(i)) { //判断映射中有没有当前值,有就直接把栈中的最后两个值弹出,然后在放进映射边的value进行计算
            stack.push(map.get(i)(stack.pop(), stack.pop()))
        } else { //没有当前值的话,直接放入栈中
            stack.push(i)
            continue;
        }
    }
    return stack.pop()
​
};

LC 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]

解题思路:

代码:

var maxSlidingWindow = function(nums, k) {
    class MonoQueue {
        
        constructor() {
            this.queue = []; 
        }
        enqueue(value) {
            let back = this.queue[this.queue.length - 1];
            while(back !== undefined && back < value) {
                this.queue.pop();
                back = this.queue[this.queue.length - 1];
            }
            this.queue.push(value)
        }
        dequeue(value) {
            let front = this.front();
            if(front === value) {
                this.queue.shift();
            }
        }
        front() {
            return this.queue[0];
        }
    }
    let helperQueue = new MonoQueue();
    let i = 0, j = 0;
    let resArr = [];
    while(j < k) {
        helperQueue.enqueue(nums[j++])
    }
    resArr.push(helperQueue.front());
    while(j < nums.length) {
        helperQueue.enqueue(nums[j]);
        helperQueue.dequeue(nums[i]);
        resArr.push(helperQueue.front());
        i++;
        j++;
    }
    return resArr;
};

\