【LeetCode与《代码随想录》】栈与队列篇:做题笔记与总结-JavaScript版

代码随想录

代码随想录
代码随想录CSDN官方

232.用栈实现队列

https://leetcode.cn/problems/implement-queue-using-stacks/


var MyQueue = function () {
    
    
    // 用栈模拟队列,需要输入栈和输出栈
    this.stackIn = []
    this.stackOut = []
};

/** 
 * @param {number} x
 * @return {void}
 */
MyQueue.prototype.push = function (x) {
    
    
    this.stackIn.push(x)
};

/**
 * @return {number}
 */
MyQueue.prototype.pop = function () {
    
    
    let temp;
    if (this.stackOut.length) {
    
    
        return this.stackOut.pop();
    }
    // out数组为空
    while (this.stackIn.length) {
    
    
        this.stackOut.push(this.stackIn.pop());
    }
    return this.stackOut.pop();
};

/**
 * @return {number}
 */
MyQueue.prototype.peek = function () {
    
    
    // 这里是this.pop而非out.pop()
    // 虽然pop是从out开始的,但out可能为空
    let temp = this.pop();
    this.stackOut.push(temp);
    return temp;
};

/**
 * @return {boolean}
 */
MyQueue.prototype.empty = function () {
    
    
    if (this.stackIn.length === 0 && this.stackOut.length === 0) return true;
    return false;
};

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

225. 用队列实现栈

https://leetcode.cn/problems/implement-stack-using-queues/

两个队列,一个用于备份。


var MyStack = function () {
    
    
    this.queue1 = []
    this.queue2 = []
};

/** 
 * @param {number} x
 * @return {void}
 */
MyStack.prototype.push = function (x) {
    
    
    this.queue1.push(x)
};

/**
 * @return {number}
 */
MyStack.prototype.pop = function () {
    
    
    // q1为空时,交换两个队列
    if (this.queue1.length === 0) {
    
    
        [this.queue1, this.queue2] = [this.queue2, this.queue1]
    }
    while (this.queue1.length > 1) {
    
    
        this.queue2.push(this.queue1.shift())
    }
    // q1只剩一个
    return this.queue1.shift()
};

/**
 * @return {number}
 */
MyStack.prototype.top = function () {
    
    
    let temp = this.pop();
    this.queue1.push(temp);
    return temp;
};

/**
 * @return {boolean}
 */
MyStack.prototype.empty = function () {
    
    
    if (this.queue1.length === 0 && this.queue2.length === 0) return true;
    return false;
};

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

20. 有效的括号

https://leetcode.cn/problems/valid-parentheses/

/**
 * @param {string} s
 * @return {boolean}
 */
var isLeft = function (s) {
    
    
    if (s === '(') return true;
    else if (s === '[') return true;
    else if (s === '{') return true;
    else return false;
}

var solve = function (l, r) {
    
    
    if (l === '[' && r === ']') return true;
    else if (l === '{' && r === '}') return true;
    else if (l === '(' && r === ')') return true;
    return false;
}

var isValid = function (s) {
    
    
    let arr = [];
    for (let i = 0; i < s.length; i++) {
    
    
        if (isLeft(s[i])) {
    
    
            arr.push(s[i]);
        } else {
    
    
            if (arr.length === 0) return false;
            else {
    
    
                let l = arr.pop();
                if (!solve(l, s[i])) return false;
            }
        }
    }
    if (arr.length === 0) return true;
    return false;
};

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

https://leetcode.cn/problems/remove-all-adjacent-duplicates-in-string/

/**
 * @param {string} s
 * @return {string}
 */
var removeDuplicates = function (s) {
    
    
    let arr = [];
    for (let i = 0; i < s.length; i++) {
    
    
        // 出栈
        if (arr.length && s[i] === arr[arr.length - 1]) {
    
    
            arr.pop();
        } else {
    
    
            arr.push(s[i]);
        }
    }
    return arr.join('');
};

150. 逆波兰表达式求值

https://leetcode.cn/problems/evaluate-reverse-polish-notation/

注意:除法要向零取整。也就是:正数向下取整(Math.floor()),负数向上取整(Math.ceil())。

/**
 * @param {string[]} tokens
 * @return {number}
 */
var evalRPN = function (tokens) {
    
    
    let arr = []
    for (const token of tokens) {
    
    
        // 是否不是数字——是符号
        if (isNaN(Number(token))) {
    
    
            let num1 = arr.pop();
            let num2 = arr.pop();
            let ans;
            switch (token) {
    
    
                case '+': {
    
    
                    ans = num1 + num2;
                    break;
                }
                case '*': {
    
    
                    ans = num1 * num2;
                    break;
                }
                case '-': {
    
    
                    ans = num2 - num1;
                    break;
                }
                case '/': {
    
    
                    // 注意:向零取整
                    if (num2 * num1 > 0) {
    
    
                        // floor向下取整
                        ans = Math.floor(num2 / num1);
                    } else {
    
    
                        // ceil向上取整
                        ans = Math.ceil(num2 / num1);
                    }
                    break;
                }
            }
            arr.push(ans);
            // console.log(ans)
        } else {
    
    
            // 数字
            arr.push(Number(token));
        }
    }
    return arr[0];
};

239. 滑动窗口最大值(困难-还没写)

https://leetcode.cn/problems/sliding-window-maximum/

347.前 K 个高频元素

https://leetcode.cn/problems/top-k-frequent-elements/

/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number[]}
 */
var topKFrequent = function (nums, k) {
    
    
    let map = new Map();
    for (const num of nums) {
    
    
        map.set(num, (map.get(num) || 0) + 1);
    }

    let arr = Array.from(map);
    // 对值排序:从大到小
    arr.sort((a, b) => (b[1] - a[1]))
    let ans = []
    for (let i = 0; i < k; i++) {
    
    
        ans.push(arr[i][0])
    }
    return ans;
};

猜你喜欢

转载自blog.csdn.net/karshey/article/details/129262562
今日推荐