Leetcode 题解 - 栈和队列

  1. Implement Queue using Stacks (Easy)

Leetcode / 力扣

栈的顺序为后进先出,而队列的顺序为先进先出。使用两个栈实现队列,一个元素需要经过两个栈才能出队列,在经过第一个栈时元素顺序被反转,经过第二个栈时再次被反转,此时就是先进先出顺序。

  1. class MyQueue {
  2. private Stack<Integer> in = new Stack<>();
  3. private Stack<Integer> out = new Stack<>();
  4. public void push(int x) {
  5. in.push(x);
  6. }
  7. public int pop() {
  8. in2out();
  9. return out.pop();
  10. }
  11. public int peek() {
  12. in2out();
  13. return out.peek();
  14. }
  15. private void in2out() {
  16. if (out.isEmpty()) {
  17. while (!in.isEmpty()) {
  18. out.push(in.pop());
  19. }
  20. }
  21. }
  22. public boolean empty() {
  23. return in.isEmpty() && out.isEmpty();
  24. }
  25. }

2. 用队列实现栈

  1. Implement Stack using Queues (Easy)

Leetcode / 力扣

在将一个元素 x 插入队列时,为了维护原来的后进先出顺序,需要让 x 插入队列首部。而队列的默认插入顺序是队列尾部,因此在将 x 插入队列尾部之后,需要让除了 x 之外的所有元素出队列,再入队列。

  1. class MyStack {
  2. private Queue<Integer> queue;
  3. public MyStack() {
  4. queue = new LinkedList<>();
  5. }
  6. public void push(int x) {
  7. queue.add(x);
  8. int cnt = queue.size();
  9. while (cnt-- > 1) {
  10. queue.add(queue.poll());
  11. }
  12. }
  13. public int pop() {
  14. return queue.remove();
  15. }
  16. public int top() {
  17. return queue.peek();
  18. }
  19. public boolean empty() {
  20. return queue.isEmpty();
  21. }
  22. }

3. 最小值栈

  1. Min Stack (Easy)

Leetcode / 力扣

  1. class MinStack {
  2. private Stack<Integer> dataStack;
  3. private Stack<Integer> minStack;
  4. private int min;
  5. public MinStack() {
  6. dataStack = new Stack<>();
  7. minStack = new Stack<>();
  8. min = Integer.MAX_VALUE;
  9. }
  10. public void push(int x) {
  11. dataStack.add(x);
  12. min = Math.min(min, x);
  13. minStack.add(min);
  14. }
  15. public void pop() {
  16. dataStack.pop();
  17. minStack.pop();
  18. min = minStack.isEmpty() ? Integer.MAX_VALUE : minStack.peek();
  19. }
  20. public int top() {
  21. return dataStack.peek();
  22. }
  23. public int getMin() {
  24. return minStack.peek();
  25. }
  26. }

对于实现最小值队列问题,可以先将队列使用栈来实现,然后就将问题转换为最小值栈,这个问题出现在 编程之美:3.7。

4. 用栈实现括号匹配

  1. Valid Parentheses (Easy)

Leetcode / 力扣

  1. "()[]{}"
  2. Output : true
  1. public boolean isValid(String s) {
  2. Stack<Character> stack = new Stack<>();
  3. for (char c : s.toCharArray()) {
  4. if (c == '(' || c == '{' || c == '[') {
  5. stack.push(c);
  6. } else {
  7. if (stack.isEmpty()) {
  8. return false;
  9. }
  10. char cStack = stack.pop();
  11. boolean b1 = c == ')' && cStack != '(';
  12. boolean b2 = c == ']' && cStack != '[';
  13. boolean b3 = c == '}' && cStack != '{';
  14. if (b1 || b2 || b3) {
  15. return false;
  16. }
  17. }
  18. }
  19. return stack.isEmpty();
  20. }

5. 数组中元素与下一个比它大的元素之间的距离

  1. Daily Temperatures (Medium)

Leetcode / 力扣

  1. Input: [73, 74, 75, 71, 69, 72, 76, 73]
  2. Output: [1, 1, 4, 2, 1, 1, 0, 0]

在遍历数组时用栈把数组中的数存起来,如果当前遍历的数比栈顶元素来的大,说明栈顶元素的下一个比它大的数就是当前元素。

  1. public int[] dailyTemperatures(int[] temperatures) {
  2. int n = temperatures.length;
  3. int[] dist = new int[n];
  4. Stack<Integer> indexs = new Stack<>();
  5. for (int curIndex = 0; curIndex < n; curIndex++) {
  6. while (!indexs.isEmpty() && temperatures[curIndex] > temperatures[indexs.peek()]) {
  7. int preIndex = indexs.pop();
  8. dist[preIndex] = curIndex - preIndex;
  9. }
  10. indexs.add(curIndex);
  11. }
  12. return dist;
  13. }

6. 循环数组中比当前元素大的下一个元素

  1. Next Greater Element II (Medium)

Leetcode / 力扣

  1. Input: [1,2,1]
  2. Output: [2,-1,2]
  3. Explanation: The first 1's next greater number is 2;
  4. The number 2 can't find next greater number;
  5. The second 1's next greater number needs to search circularly, which is also 2.

与 739. Daily Temperatures (Medium) 不同的是,数组是循环数组,并且最后要求的不是距离而是下一个元素。

public int[] nextGreaterElements(int[] nums) {
    int n = nums.length;
    int[] next = new int[n];
    Arrays.fill(next, -1);
    Stack<Integer> pre = new Stack<>();
    for (int i = 0; i < n * 2; i++) {
        int num = nums[i % n];
        while (!pre.isEmpty() && nums[pre.peek()] < num) {
            next[pre.pop()] = num;
        }
        if (i < n){
            pre.push(i);
        }
    }
    return next;
}