【代码随想录Day59】单调栈

503 下一个更大元素II

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

遍历两次

class Solution {
    public int[] nextGreaterElements(int[] nums) {
        int[] result = new int[nums.length];
        Arrays.fill(result, -1);
        Deque stack = new ArrayDeque<>();
        for (int j = 0; j < 2; j++) {
            for (int i = nums.length - 1; i >= 0; i--) {
                while (!stack.isEmpty() && stack.peekFirst() <= nums[i]) {
                    stack.pollFirst();
                }
                if (!stack.isEmpty()) result[i] = stack.peekFirst();
                stack.offerFirst(nums[i]);
            }
        }
        return result;
    }
}

42 接雨水

https://leetcode.cn/problems/trapping-rain-water/ 单调栈做法没看懂

class Solution {  //双指针
    public int trap(int[] height) {
        int i = 0, j = height.length - 1;
        int sum = 0, level = 0;
        while (i <= j) {
            level = Math.max(level, Math.min(height[i], height[j])); //有原level兜底,如果两边短板变高了level可更高
            if (height[i] <= height[j]) {
                sum += level - height[i++];
            } else {
                sum += level - height[j--];
            }
        }
        return sum;
    }
}

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