代码随想录算法训练营第五十九天| 503.下一个更大元素II 42. 接雨水

代码随想录算法训练营第五十九天| 503.下一个更大元素II 42. 接雨水

一、力扣503.下一个更大元素II

题目链接
思路:数组是循环的,只需要在遍历时,遍历2遍,然后存下标时,i % len即可

class Solution {
    public int[] nextGreaterElements(int[] nums) {
        int len = nums.length;
        int[] res = new int[len];
        Arrays.fill(res, -1);
        Deque<Integer> stack = new LinkedList<>();
        stack.push(0);
        for (int i = 1; i < len * 2; i++) {
            int index = i % len;
            while (!stack.isEmpty() && nums[index] > nums[stack.peek()]) {
                res[stack.peek()] = nums[index];
                stack.pop();
            }
            stack.push(index);
        }
        return res;
    }
}

二、力扣42. 接雨水

题目链接
思路:
双指针法:用两个数组分别记录每一个位置左边的最大值和右边的最大值,如果没有更大的,他本身就是最大值。
计算雨水时,要用两侧最大值中的最小值减去当前高度,Math.min(leftMax[i], rightMax[i]) - height[i],只搜集大于0的。

class Solution {
    public int trap(int[] height) {
        if (height.length <= 2) return 0;
        int len = height.length, sum = 0;
        int[] leftMax = new int[len];
        int[] rightMax = new int[len];
        leftMax[0] = height[0];
        for (int i = 1; i < len; i++) {
            leftMax[i] = Math.max(height[i], leftMax[i-1]);
        }
        rightMax[len - 1] = height[len - 1];
        for (int i = len-2; i >= 0; i--) {
            rightMax[i] = Math.max(height[i], rightMax[i+1]);
        }
        for (int i = 0; i < len; i++) {
            int temp = Math.min(leftMax[i], rightMax[i]) - height[i];
            if (temp > 0) {
                sum += temp;
            }
        }
        return sum;
    }
}

单调栈法,计算高度差和宽度,当前元素大于栈顶即栈顶是凹槽。

class Solution {
    public int trap(int[] height) {
        if (height.length <= 2) return 0;
        int len = height.length, sum = 0;
        Deque<Integer> stack = new LinkedList<>();
        stack.push(0);
        for (int i = 1; i < len; i++) {
            if (height[i] < height[stack.peek()]) {
                stack.push(i);
            }else if (height[i] == height[stack.peek()]) {
                stack.pop();
                stack.push(i);
            }else {
                while (!stack.isEmpty() && height[i] > height[stack.peek()]) {
                    int mid = stack.pop();
                    if (!stack.isEmpty()) {
                        int h = Math.min(height[i], height[stack.peek()]) - height[mid];
                        int w = i - stack.peek() - 1;
                        sum += h * w;
                    }
                }
                stack.push(i);
            }
        }
        return sum;
    }
}

你可能感兴趣的:(算法)