【近日力扣】栈排序+最小栈+用队列实现栈

JS 对太友好了,如果想体会原汁原味的栈(先进后出),那就不要在栈底操作元素,比如使用shift()方法,而且排序也不要调用 API

排序栈(中等)

  • 思路:辅助栈
    • 每次要取最小元素,那意味着在取的时候排序?思考一会便知道不现实——题目要求顶多两个栈,如果存数据的栈里面是乱序,至少得三个栈才能完成排序
    • 所以可以计划在存数据时就进行排序,你会发现两个栈足够了。每当存入一个数val,就与栈顶的数top做比较,如果val大,就把top取出放入辅助栈,如果val小,就直接存入(维持最小值在栈顶)
    • 最后一步在把辅助栈的元素存回数据栈就好(怎么出来怎么回去),其他步骤都是小case了
var SortedStack = function() {
  	this.stack = []
  	this.copy = [] // 辅助栈
};

SortedStack.prototype.push = function(val) {
  	// 数据栈不为空且栈顶小于val
  	while (this.stack.length && this.stack[this.stack.length - 1] < val) {
    	this.copy.push(this.stack.pop())
  	}

  	this.stack.push(val) // 在合适的位置存入val

 	// 把辅助栈的元素倒入数据栈
  	while (this.copy.length) {
    	this.stack.push(this.copy.pop())
  	}

};

SortedStack.prototype.pop = function() {
	this.stack.length && this.stack.pop()
};

SortedStack.prototype.peek = function() {
  	return this.stack.length === 0 ? -1 : this.stack[this.stack.length - 1]
};

SortedStack.prototype.isEmpty = function() {
  	return this.stack.length === 0 ? true : false
};

最小栈(简单)

  • 思路:一个数据栈加一个辅助栈,每当数据栈加入元素时,辅助栈也加入元素,该元素为数据栈中此时对应的最小值。比如数据栈加入1,辅助栈加入1,数据栈加入2,辅助栈还是加入1,当数据栈栈顶元素被取出时辅助栈栈顶元素也取出,所以辅助栈中永远保存着当前的最小值
var MinStack = function() {
    this.stack = []
    this.help = []
};

MinStack.prototype.push = function(val) {
    if (!this.stack.length) {
        this.help.push(val)
    } else {
        let top = this.help[this.help.length - 1]
        top > val ? this.help.push(val) : this.help.push(top)
    }
    this.stack.push(val)
};

MinStack.prototype.pop = function() {
    this.stack.pop()
    this.help.pop()
};

MinStack.prototype.top = function() {
    return this.stack[this.stack.length - 1]
};

MinStack.prototype.getMin = function() {
    return this.help[this.help.length - 1]
};

用队列实现栈(简单)

  • 思路:关键点在于push部分的实现,要用两个队列的先进先出来模拟一个栈的先进后出
var MyStack = function() {
    this.queue1 = []
    this.queue2 = []
};

MyStack.prototype.push = function(x) {
    this.queue2.push(x);
    while (this.queue1.length) this.queue2.push(this.queue1.shift());
    [this.queue1, this.queue2] = [this.queue2, this.queue1];
};

MyStack.prototype.pop = function() {
    return this.queue1.shift()
};

MyStack.prototype.top = function() {
    return this.queue1[0]
};

MyStack.prototype.empty = function() {
    if (this.queue1.length) {
        return false
    } else {
        return true
    }
};

如果觉得对你有帮助的话,点个赞呗~

反正发文又不赚钱,交个朋友呗~

如需转载,请注明出处foolBirdd

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值