Day11: 栈与队列基础 ||

150. 逆波兰表达式求值

向零截断: Math.trunc

注意 除法 和 减法 的两个数的顺序:

case '-': numStack.push( - numStack.pop() + numStack.pop()); break;
case '/': numStack.push(Math.trunc(1 / numStack.pop() * numStack.pop())); break;

function evalRPN(tokens: string[]): number {
    let numStack = [];
    let opeStack = [];
    for(let token of tokens){
        if(['+', '-', '*', '/'].includes(token)){
            switch(token){
                case '+': numStack.push(numStack.pop() + numStack.pop()); break;
                case '-': numStack.push( - numStack.pop() + numStack.pop()); break;
                case '*': numStack.push(numStack.pop() * numStack.pop()); break;
                case '/': numStack.push(Math.trunc(1 / numStack.pop() * numStack.pop())); break;
            }
        } else {
            numStack.push(Number(token));
        }
    }
    return numStack.pop();
};

239. 滑动窗口最大值

function slideWindow(nums: number[], window: number[], i: number, k: number): void{
    // 需要判断第一个元素是否过期, 所以把 window 里面存的值改为索引,方便判断 window[0] === i - k
    if(window.length === k || window[0] === i - k) window.shift();
    while(nums[i] >= nums[window[window.length - 1]]){
        window.pop();   
    }
    window.push(i);
}
function maxSlidingWindow(nums: number[], k: number): number[] {
    let results = [];
    let window = [];
    for(let i = 0; i < nums.length; i++){
        slideWindow(nums, window, i, k);
        if(i >= k - 1) results.push(nums[window[0]]);
    }
    return results;
};

347.前 K 个高频元素

function topKFrequent(nums: number[], k: number): number[] {
    let frequenceMap = new Map();
    for(let num of nums){
        if(!frequenceMap.get(num)) frequenceMap.set(num, 1);
        else frequenceMap.set(num, frequenceMap.get(num) + 1);
    }
    let results = Array.from(frequenceMap);
    results.sort((a, b) => b[1] - a[1]);
    return (results.map(arr => arr[0])).slice(0, k);
};

官方题解:

转成集合这里可以参考官方题解:
countMap.set(num, (countMap.get(num) || 0) + 1);

排序这里也是官方题解更精简:

[...countMap.entries()]
        .sort((a, b) => b[1] - a[1])
        .slice(0, k)
        .map(i => i[0]);

function topKFrequent(nums: number[], k: number): number[] {
    const countMap: Map<number, number> = new Map();
    for (let num of nums) {
        countMap.set(num, (countMap.get(num) || 0) + 1);
    }
    // tS没有最小堆的数据结构,所以直接对整个数组进行排序,取前k个元素
    return [...countMap.entries()]
        .sort((a, b) => b[1] - a[1])
        .slice(0, k)
        .map(i => i[0]);
};

但这个题本质上是要考小顶堆

小顶堆
// js 没有堆 需要自己构造
class Heap {
    constructor(compareFn) {
        this.compareFn = compareFn;
        this.queue = [];
    }

    // 添加
    push(item) {
        // 推入元素
        this.queue.push(item);

        // 上浮
        let index = this.size() - 1; // 记录推入元素下标
        let parent = Math.floor((index - 1) / 2); // 记录父节点下标

        while (parent >= 0 && this.compare(parent, index) > 0) { // 注意compare参数顺序
            [this.queue[index], this.queue[parent]] = [this.queue[parent], this.queue[index]];

            // 更新下标
            index = parent;
            parent = Math.floor((index - 1) / 2);
        }
    }

    // 获取堆顶元素并移除
    pop() {
        // 边界情况,只有一个元素或没有元素应直接弹出
        if (this.size() <= 1) {
            return this.queue.pop()
        }

        // 堆顶元素
        const out = this.queue[0];

        // 移除堆顶元素 填入最后一个元素
        this.queue[0] = this.queue.pop();

        // 下沉
        let index = 0; // 记录下沉元素下标
        let left = 1; // left 是左子节点下标 left + 1 则是右子节点下标
        let searchChild = this.compare(left, left + 1) > 0 ? left + 1 : left;

        while (this.compare(index, searchChild) > 0) { // 注意compare参数顺序
            [this.queue[index], this.queue[searchChild]] = [this.queue[searchChild], this.queue[index]];

            // 更新下标
            index = searchChild;
            left = 2 * index + 1;
            searchChild = this.compare(left, left + 1) > 0 ? left + 1 : left;
        }

        return out;
    }

    size() {
        return this.queue.length;
    }

    // 使用传入的 compareFn 比较两个位置的元素
    compare(index1, index2) {
        // 处理下标越界问题
        if (this.queue[index1] === undefined) return 1;
        if (this.queue[index2] === undefined) return -1;

        return this.compareFn(this.queue[index1], this.queue[index2]);
    }

}

const topKFrequent = function (nums, k) {
    const map = new Map();

    for (const num of nums) {
        map.set(num, (map.get(num) || 0) + 1);
    }

    // 创建小顶堆
    const heap= new Heap((a, b) => a[1] - b[1]);

    // entry 是一个长度为2的数组,0位置存储key,1位置存储value
    for (const entry of map.entries()) {
        heap.push(entry);

        if (heap.size() > k) {
            heap.pop();
        }
    }

    // return heap.queue.map(e => e[0]);

    const res = [];

    for (let i = heap.size() - 1; i >= 0; i--) {
        res[i] = heap.pop()[0];
    }

    return res;
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值