1、滑动窗口最大值(239)
地址:https://leetcode-cn.com/problems/sliding-window-maximum/
/*** @param {number[]} nums* @param {number} k* @return {number[]}*/const maxSlidingWindow = function (nums, k) {// 缓存数组的长度const len = nums.length;// 定义结果数组const res = [];// 初始化左指针let left = 0;// 初始化右指针let right = k - 1;// 当数组没有被遍历完时,执行循环体内的逻辑while (right < len) {// 计算当前窗口内的最大值const max = calMax(nums, left, right);// 将最大值推入结果数组res.push(max);// 左指针前进一步left++;// 右指针前进一步right++;}// 返回结果数组return res;};// 这个函数用来计算最大值function calMax(arr, left, right) {// 处理数组为空的边界情况if (!arr || !arr.length) {return;}// 初始化 maxNum 的值为窗口内第一个元素let maxNum = arr[left];// 遍历窗口内所有元素,更新 maxNum 的值for (let i = left; i <= right; i++) {if (arr[i] > maxNum) {maxNum = arr[i];}}// 返回最大值return maxNum;}
2、用栈实现一个队列(232)
地址:https://leetcode-cn.com/problems/implement-queue-using-stacks/
/*** 初始化构造函数*/const MyQueue = function () {// 初始化两个栈this.stack1 = [];this.stack2 = [];};/*** Push element x to the back of queue.* @param {number} x* @return {void}*/MyQueue.prototype.push = function (x) {// 直接调度数组的 push 方法this.stack1.push(x);};/*** Removes the element from in front of queue and returns that element.* @return {number}*/MyQueue.prototype.pop = function () {// 假如 stack2 为空,需要将 stack1 的元素转移进来if (this.stack2.length <= 0) {// 当 stack1 不为空时,出栈while (this.stack1.length !== 0) {// 将 stack1 出栈的元素推入 stack2this.stack2.push(this.stack1.pop());}}// 为了达到逆序的目的,我们只从 stack2 里出栈元素return this.stack2.pop();};/*** Get the front element.* @return {number}* 这个方法和 pop 唯一的区别就是没有将定位到的值出栈*/MyQueue.prototype.peek = function () {if (this.stack2.length <= 0) {// 当 stack1 不为空时,出栈while (this.stack1.length != 0) {// 将 stack1 出栈的元素推入 stack2this.stack2.push(this.stack1.pop());}}// 缓存 stack2 的长度const stack2Len = this.stack2.length;return stack2Len && this.stack2[stack2Len - 1];};/*** Returns whether the queue is empty.* @return {boolean}*/MyQueue.prototype.empty = function () {// 若 stack1 和 stack2 均为空,那么队列空return !this.stack1.length && !this.stack2.length;};
