LeetCode-栈和队列总结

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Apple_hzc/article/details/83902037

栈和队列

栈和队列是很重要的数据结构,栈是先进后出,队列是先进先出,可以用两个栈实现队列,也可以用一个队列实现栈,这些基本操作都应该掌握熟练。

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

739. Daily Temperatures (Medium)

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

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

class Solution {
    public int[] dailyTemperatures(int[] T) {
        if (null == T || 0 == T.length) {
            return null;
        }
        int n = T.length;
        int[] result = new int[n];
        Stack<Integer> stack = new Stack<>();
        stack.push(0);
        for (int i = 1; i < n; i++) {
            while (!stack.isEmpty() && T[i] > T[stack.peek()]) {
                result[stack.peek()] = i - stack.peek();
                stack.pop();
            }
            stack.push(i);
        }
        return result;
    }
}

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

503. Next Greater Element II (Medium)

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

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

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

猜你喜欢

转载自blog.csdn.net/Apple_hzc/article/details/83902037
今日推荐