【代码随想录Day58】单调栈

739 每日温度

https://leetcode.cn/problems/daily-temperatures/

class Solution {   //从前向后遍历,碰到更大的来了就倒出来,被倒出来的是能找到更大温度的,留在栈里的是找不到右边更大温度的。
    public int[] dailyTemperatures(int[] temperatures) {
        Deque stack = new ArrayDeque<>();
        int[] result = new int[temperatures.length];
        for (int i = 0; i < temperatures.length; i++) {
            while (!stack.isEmpty() && temperatures[stack.peekFirst()] < temperatures[i]) {
                int pre = stack.pollFirst();
                result[pre] = i - pre;
            }
            stack.offerFirst(i);
        }
        return result;
    }
}
class Solution {  //从后往前遍历,又老又小的没有保存的必要了,老小的倒出来。
    public int[] dailyTemperatures(int[] temperatures) {
        Deque stack = new ArrayDeque<>();
        int[] result = new int[temperatures.length];
        for (int i = temperatures.length - 1; i >= 0; i--) {
            while (!stack.isEmpty() && temperatures[stack.peekFirst()] <= temperatures[i]) {
                stack.pollFirst();
            }
            if (!stack.isEmpty()) result[i] = stack.peekFirst() - i;
            stack.offerFirst(i);
        }
        return result;
    }
}

496下一个更大元素 I

https://leetcode.cn/problems/next-greater-element-i/

用一个map来预处理找出nums1里有没有这个数。

class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        Map map = new HashMap<>();
        for (int i = 0; i < nums1.length; i++) {
            map.put(nums1[i], i);
        }
        int[] result = new int[nums1.length];
        Deque stack = new ArrayDeque<>();
        for (int i = nums2.length - 1; i >= 0; i--) {
            while (!stack.isEmpty() && nums2[stack.peekFirst()] <= nums2[i]) {
                stack.pollFirst();
            }
            if (map.containsKey(nums2[i])) {
                result[map.get(nums2[i])] = stack.isEmpty() ? -1 : nums2[stack.peekFirst()];
            }
            stack.offerFirst(i);
        }
        return result;
    }
}

你可能感兴趣的:(代码随想录,算法,leetcode)