varMyQueue=function(){this.stackIn =[]this.stackOut =[]};/**
* @param {number} x
* @return {void}
*/MyQueue.prototype.push=function(x){this.stackIn.push(x)};/**
* @return {number}
*/MyQueue.prototype.pop=function(){const size =this.stackOut.length
if(size){returnthis.stackOut.pop()}while(this.stackIn.length){this.stackOut.push(this.stackIn.pop())}returnthis.stackOut.pop()};/**
* @return {number}
*/MyQueue.prototype.peek=function(){const x =this.pop()this.stackOut.push(x)return x
};/**
* @return {boolean}
*/MyQueue.prototype.empty=function(){return!this.stackIn.length &&!this.stackOut.length
};/**
* Your MyQueue object will be instantiated and called as such:
* var obj = new MyQueue()
* obj.push(x)
* var param_2 = obj.pop()
* var param_3 = obj.peek()
* var param_4 = obj.empty()
*/
225. 用队列实现栈
varMyStack=function(){this.queue1 =[]this.queue2 =[]};/**
* @param {number} x
* @return {void}
*/MyStack.prototype.push=function(x){this.queue1.push(x)};/**
* @return {number}
*/MyStack.prototype.pop=function(){if(!this.queue1.length){[this.queue1,this.queue2]=[this.queue2,this.queue1]}while(this.queue1.length>1){this.queue2.push(this.queue1.shift())}returnthis.queue1.shift()};/**
* @return {number}
*/MyStack.prototype.top=function(){const x =this.pop()this.queue1.push(x)return x
};/**
* @return {boolean}
*/MyStack.prototype.empty=function(){return!this.queue1.length &&!this.queue2.length
};/**
* Your MyStack object will be instantiated and called as such:
* var obj = new MyStack()
* obj.push(x)
* var param_2 = obj.pop()
* var param_3 = obj.top()
* var param_4 = obj.empty()
*/
20. 有效的括号
/**
* @param {string} s
* @return {boolean}
*/varisValid=function(s){const stack =[];let left ="({[";let right =")}]";for(let ch of s){if(left.includes(ch)){
stack.push(ch);}if(right.includes(ch)){let top = stack[stack.length -1];if(top ===undefined)returnfalse;if((ch ==="}"&& top ==="{")||(ch ===")"&& top ==="(")||(ch ==="]"&& top ==="[")){
stack.pop();}else{returnfalse}}}return stack.length ===0};
1047. 删除字符串中的所有相邻重复项
/**
* @param {string} s
* @return {string}
*/varremoveDuplicates=function(s){const stack =[]for(let ch of s){if(stack.length){
top = stack[stack.length-1]if(top===ch){
stack.pop()}else{
stack.push(ch)}}else{
stack.push(ch)}}return stack.join('')};
150. 逆波兰表达式求值
/**
* @param {string[]} tokens
* @return {number}
*/varevalRPN=function(tokens){const s =newMap([["+",(a, b)=> a *1+ b *1],["-",(a, b)=> b - a],["*",(a, b)=> b * a],["/",(a, b)=>(b / a)|0]]);const stack =[];for(const i of tokens){if(!s.has(i)){
stack.push(i);continue;}
stack.push(s.get(i)(stack.pop(), stack.pop()))}return stack.pop();};
347. 前 K 个高频元素
/**
* @param {number[]} nums
* @param {number} k
* @return {number[]}
*/vartopKFrequent=function(nums, k){const map ={};for(let ch of nums){
map[ch]===undefined?(map[ch]=1):(map[ch]+=1);}let arr = Object.entries(map);// 注意排序
arr.sort((a, b)=> b[1]- a[1]);let ans =[];for(let i =0; i < k; i++){
ans.push(arr[i][0]);}return ans;};