You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
/** * initialize your data structure here. */varMinStack=function(){this.stack=[]this.minValue=Number.MAX_VALUE//假定,为什么0不可以};/** * @param {number} x * @return {void} */MinStack.prototype.push=function(x){varitem=x-this.minValueif(item<0){this.minValue=x}this.stack.push(item)};/** * @return {void} */MinStack.prototype.pop=function(){varitem=this.stack.pop()//item = x - minif(item<0){this.minValue=this.minValue-item}};/** * @return {number} */MinStack.prototype.top=function(){if(!this.stack.length){returnnull}else{varrealValue=this.minValue-this.stack[0]returnrealValue}};/** * @return {number} */MinStack.prototype.min=function(){if(!this.stack.length){returnnull}else{returnthis.minValue}};/** * Your MinStack object will be instantiated and called as such: * var obj = new MinStack() * obj.push(x) * obj.pop() * var param_3 = obj.top() * var param_4 = obj.min() */
varMaxQueue=function(){this.queue1=[]this.queue2=[]};/** * @return {number} */MaxQueue.prototype.max_value=function(){if(this.queue2.length){returnthis.queue2[0];}return-1;};/** * @param {number} value * @return {void} */MaxQueue.prototype.push_back=function(value){this.queue1.push(value);//队列1存储所有元素while(this.queue2.length&&this.queue2[this.queue2.length-1]<value){this.queue2.pop();}//将队列2的元素从后往前和当前插入元素比较,如果出现大于当前插入元素的数据便停止this.queue2.push(value);//从队头插入当前元素,保证比后面的元素要小};/** * @return {number} */MaxQueue.prototype.pop_front=function(){if(!this.queue1.length){return-1;}constvalue=this.queue1.shift();//队列1弹出元素if(value===this.queue2[0]){this.queue2.shift();//队列2}returnvalue;};/** * 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.shift_front() */
The text was updated successfully, but these errors were encountered:
用两个栈实现一个队列
队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
示例 1:
实例2:
1 <= values <= 10000
最多会对 appendTail、deleteHead 进行 10000 次调用
解题思路:
队列先进后出
栈1队头,栈2队尾
队列增=栈1.push(value)、队列减=栈2.pop()
情况:
1.栈2没有出列元素,那么:
1.1 栈1出栈、栈2进栈,最后栈2出栈的元素,即为该次需要模拟的出队元素
1.2 栈1没有元素,返回-1
代码:
包含min函数的栈
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
提示:
各函数的调用总次数不超过 20000 次
解题思路:
代码:
队列最大值
请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。
若队列为空,pop_front 和 max_value 需要返回 -1
示例 1:
解题思路:
代码:
The text was updated successfully, but these errors were encountered: