【数据结构与算法】2.队列

108 阅读1分钟

队列是一种先进先出的数据结构。

const queue = [];
queue.push(1);
queue.push(2);
const item1 = queue.shift();//1
const item2 = queue.shift();//2

那么我们有哪些场景会用到队列呢?

 

其实对于前端来说,我们很熟悉的浏览器执行各种各样的用户事件,网络请求,以及页面渲染,脚本执行背后依靠的都是事件队列来支撑。

 

日常生活中的排队也是一种队列很常见的场景。

 

还有一种场景就是最近请求次数。

image.png  

var RecentCounter = function() {
    this.queue = []
};


/** 
 * @param {number} t
 * @return {number}
 */
RecentCounter.prototype.ping = function(t) {
    this.queue.push(t) // 首先让时刻入栈
   // 检查一下对头时刻 若不在[t-3000,t]的区间内,则出队 
   // 比如[3002 - 3000,3002] = [2,3002] 此时 1 不在队列中,得出队
    while(this.queue[0] < t - 3000){
        this.queue.shift()
    }
    // 最终队列的长度就是在区间内的请求个数
    return this.queue.length
};


/**
 * Your RecentCounter object will be instantiated and called as such:
 * var obj = new RecentCounter()
 * var param_1 = obj.ping(t)
 */