1. 程式人生 > >LeetCode-棧和佇列總結

LeetCode-棧和佇列總結

棧和佇列

棧和佇列是很重要的資料結構,棧是先進後出,佇列是先進先出,可以用兩個棧實現佇列,也可以用一個佇列實現棧,這些基本操作都應該掌握熟練。

陣列中元素與下一個比它大的元素之間的距離

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;
    }
}