Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

队列的最大值 #369

Open
lzxjack opened this issue Jan 11, 2023 · 1 comment
Open

队列的最大值 #369

lzxjack opened this issue Jan 11, 2023 · 1 comment

Comments

@lzxjack
Copy link
Contributor

lzxjack commented Jan 11, 2023

No description provided.

@lxy-Jason
Copy link
Contributor

var MaxQueue = function() {
    this.arr = []
    this.maxArr = [] //这里要用一个数组,是因为pop可能会把最大数给删除
};

/**
 * @return {number}
 */
MaxQueue.prototype.max_value = function() {
    return this.arr.length ? this.maxArr[0] : -1
};

/** 
 * @param {number} value
 * @return {void}
 */
MaxQueue.prototype.push_back = function(value) {
    this.arr.push(value) 
    while(this.maxArr.length && this.maxArr[this.maxArr.length - 1] < value){
        this.maxArr.pop() //比push进来的数小的,可以直接删除,因为这是队列
    }
    this.maxArr.push(value)
};

/**
 * @return {number}
 */
MaxQueue.prototype.pop_front = function() {
    if(!this.arr.length) return -1
    const temp = this.arr.shift();
    if(temp === this.maxArr[0]){
        this.maxArr.shift()
    }
    return temp
};

/**
 * Your MaxQueue object will be instantiated and called as such:
 * var obj = new MaxQueue()
 * var param_1 = obj.max_value()
 * obj.push_back(value)
 * var param_3 = obj.pop_front()
 */

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants