JavaScript中,不应该用数组实现Queue

今天遇到一件有趣的事情,一开始,我只是一不小心,用了shift/unshift实现stack。最后却得出了一个结论,不应该用数组实现Queue。这点恐怕和社区里很多人的做法相左。不过,我实现的Queue,比用数组实现快一倍。如果你在乎性能,可以参考一下。

现象

今天做leetcode,用了shift/unshift实现stack,结果很慢。

/**
 * @param {number[]} temperatures
 * @return {number[]}
 */
function dailyTemperatures (temperatures) {
    const n = temperatures.length;
    const stack = [0];
    const ans = Array(n).fill(0);
    for (let i = 1; i<n;i++) {
        while (stack.length>0 && temperatures[i] > temperatures[stack[stack.length-1]]){
            const previous = stack.shift();
            ans[previous] = i - previous;
        }
        stack.unshift(i);
    }
    return ans;
}

在这里插入图片描述

我一直想不通,和速度最快的答案比较,发现唯一的区别就是别人用的是pop/push。于是改成了pop/push,结果马上就变快了。

/**
 * @param {number[]} temperatures
 * @return {number[]}
 */
function dailyTemperatures (temperatures) {
    const n = temperatures.length;
    const stack = [0];
    const ans = Array(n).fill(0);
    for (let i = 1; i<n;i++) {
        while (stack.length>0 && temperatures[i] > temperatures[stack[stack.length-1]]){
            const previous = stack.pop();
            ans[previous] = i - previous;
        }
        stack.push(i);
    }
    return ans;
}

在这里插入图片描述

分析

我想不通为什么会有这么大的差别。如果JavaScript的内部是ListNode。那么用pop/push是在尾部操作,用shift/unshift是在头部操作。两者都需要添加一个ListNode。区别就是,在头部插入,需要让head指针指向新插入的ListNode,或者第二个ListNode。也许就是这么一个小的操作,导致shift/unshift比pop/push慢吧。

查了stackoverflow,答案是

To remove the returned item without re-addressing the array and invalidating all references to it, shift() requires moving the entire array around; pop() can simply subtract 1 from its length.

原来是这样的,增减头,导致所有的元素的编号都要重新计算。这就是JavaScript array的问题了。在这个数据类型中,实现了太多的功能。导致于,我明明只需要使用stack的功能,但是其内部却在给我计算index。

那么,新的问题来了,用array实现stack,可以避开re-indexing。但是如果要实现queue,那无论如何都无法避开了。

证实,并实现快速的Queue

为了证实我的猜测,我们再拿一道leetcode做实验。这里,我们用 1823. Find the Winner of the Circular Game.

我们先用javascript的array实现。

/**
 * @param {number} n
 * @param {number} k
 * @return {number}
 */
function findTheWinner (n, k) {
    const q = [];
    for(let i=0;i<n;i++) {
        q.push(i+1);
    }

    let count = 1;
    while(q.length > 1) {
        const v = q.shift();
        if (count % k !== 0){
            q.push(v);
        }
        count++;
    }

    return q[0];
}

在这里插入图片描述
然后,我们自己实现一个Queue。

const Queue = function () {
    this.first = null;
    this.last = null;
    this.size = 0;
};

const Node = function (data) {
    this.data = data;
    this.next = null;
};

Queue.prototype.enqueue = function (data) {
    const node = new Node(data);
    if(this.last) {
        this.last.next = node;
        this.last = node;
    }

    if (!this.first) {
        this.first = node;
        this.last = node;
    }

    this.size += 1;
    return node;
};

Queue.prototype.dequeue = function () {
    temp = this.first;
    this.first = this.first.next;
    if (!this.first) {
        this.last = null;
    }
    this.size -= 1;
    return temp.data;
};

/**
 * @param {number} n
 * @param {number} k
 * @return {number}
 */
function findTheWinner(n, k) {
    const q = new Queue();
    for (let i = 0; i < n; i++) {
        q.enqueue(i + 1);
    }

    let count = 1;
    while (q.size > 1) {
        const v = q.dequeue();
        if (count % k !== 0) {
            q.enqueue(v);
        }
        count++;
    }

    return q.dequeue();
}

我们再次提交到leetcode,这时,速度已经快了一倍。

在这里插入图片描述

class的写法

在leetcode提交的时候,无法使用class,报错说已经被定义了。我print了一下它自定义的class,里面还是用的数组。我就没继续研究了。

class Node {
    constructor(val) {
        this.val = val;
        this.next = null;
    }
}

class Queue{
    constructor(){
        this.first = null;
        this.last = null;
        this.size = 0;
    }

    enqueue (val) {
        const node = new Node(val);
        if(this.last) {
            this.last.next = node;
            this.last = node;
        }
    
        if (!this.first) {
            this.first = node;
            this.last = node;
        }
    
        this.size += 1;
        return node;
    }

    dequeue() {
        const temp = this.first;
        this.first = this.first.next;
        if (!this.first) {
            this.last = null;
        }
        this.size -= 1;
        return temp.val;
    }
}

号外

当然这道题本身的最佳答案并不是使用Queue,我用这道题Queue测试,是因为他用Queue比较多。

在这里插入图片描述
另外,我前几天买了leetcode会员,所以可以短时间反复提交,还是有点用的。一天才8元,也不贵。(希望CSDN不要把本文自动识别成广告)

总结

在Javascript中,用数组实现了多种功能(相当于其他语言里的Array, List, Queue, Stack),导致了一些无谓的浪费。尤其对于Queue来说,用数组实现Queue,造成每次Enqueue的时候,无端地重算数组下标。在追求速度地场景中,只能自己实现Queue了。或者找一找第三方库。

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

织网者Eric

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值