面试题 03.05. 栈排序

面试题 03.05. 栈排序

栈排序。 编写程序,对栈进行排序使最小元素位于栈顶。最多只能使用一个其他的临时栈存放数据,但不得将元素复制到别的数据结构(如数组)中。该栈支持如下操作:push、pop、peek 和 isEmpty。当栈为空时,peek 返回 -1。

示例1:

输入:
[“SortedStack”, “push”, “push”, “peek”, “pop”, “peek”]
[[], [1], [2], [], [], []]
输出:
[null,null,null,1,null,2]

示例2:

输入:
[“SortedStack”, “pop”, “pop”, “push”, “pop”, “isEmpty”]
[[], [], [], [1], [], []]
输出:
[null,null,null,null,null,true]

** 解题思路**

  1. 暴力解法

题目要求要维护一个排好序的栈,则意味这在每次栈中元素数目变化后,即pop或push后,栈仍然是一个排序栈,pop不影响,push需要考虑,最简单的方法就是插入,即将要push的值插入到栈中对应位置,维护排序栈。将小于val的值放入辅助栈,push(val),然后再从辅助栈中将其他元素挪回。

class SortedStack {
  Stack<Integer> stack, temp;

  public SortedStack() {
    stack = new Stack<>();
    temp = new Stack<>();
  }

 public void push(int val) {
    if (stack.isEmpty())    stack.push(val);
    else {
      while (!stack.isEmpty() && stack.peek() < val)
        temp.push(stack.pop());
      stack.push(val);
      while (!temp.isEmpty())
        stack.push(temp.pop());
    }
  }

  public void pop() {
    if (!stack.isEmpty()) stack.pop();
  }

  public int peek() {
    if (stack.isEmpty()) return -1;
    return stack.peek();
  }

  public boolean isEmpty() {
    return stack.isEmpty();
  }
}
  1. 优化算法

通过查看提示我们得知有可以优化的算法,具体思考,我们再push一个值需要将前面的元素移到辅助栈再移回来,我们可以同时维护辅助栈和数据栈来减少重复移动。
假设要push的元素为x:

  • x小于数据栈的栈顶:将辅助栈大于x的移入数据栈,xpush到辅助栈。
  • x大于数据栈的栈顶:将数据栈小于x的移入辅助栈,xpush到数据栈。
  • 在执行pop及peek时需要合并栈。
class SortedStack {
  Stack<Integer> stack, temp;

  public SortedStack() {
    stack = new Stack<>();
    temp = new Stack<>();
  }

  public void push(int val) {
    if (stack.isEmpty()) stack.push(val);
    else {
      if (stack.peek() > val) {
        if (temp.isEmpty()) temp.push(val);
        else {
          while (!temp.isEmpty() && temp.peek() > val) stack.push(temp.pop());
          temp.push(val);
        }
      } else {
        while (!stack.isEmpty() && stack.peek() < val) temp.push(stack.pop());
        stack.push(val);
      }
    }
  }

  public void pop() {
    if (stack.isEmpty() && temp.isEmpty()) return;
    while (!temp.isEmpty()) {
      stack.push(temp.pop());
    }
    stack.pop();
  }

  public int peek() {
    if (stack.isEmpty() && temp.isEmpty()) return -1;
    while (!temp.isEmpty()) {
      stack.push(temp.pop());
    }
    int res = stack.peek();
    return res;
  }

  public boolean isEmpty() {
    return stack.isEmpty()&&temp.isEmpty();
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值