代码随想录算法训练营 Day 59 | 503.下一个更大元素II,42.接雨水

503.下一个更大元素II

讲解链接:代码随想录-503.下一个更大元素II

跟(42.接雨水)思路一样,不过因为数组收尾相连,循环数是数组长度的两倍,循环里面做下下标处理就可以了。

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

42.接雨水

讲解链接:代码随想录-42.接雨水

单调栈
public int trap(int[] height) {
    int len = height.length;
    if (len <= 2) {
        return 0;
    }
    Deque<Integer> stack = new LinkedList<>();
    stack.push(0);
    int sum = 0;
    for (int i = 1; i < len; i++) {
        if (height[i] < height[stack.peek()]) {

        } else if (height[i] == height[stack.peek()]) {
            stack.pop();
        } else if (height[i] > height[stack.peek()]) {
            while (!stack.isEmpty() && height[i] > height[stack.peek()]) {
                int mid = stack.pop();
                if (!stack.isEmpty()) {
                    int left = stack.peek();
                    int h = Math.min(height[i], height[left]) - height[mid];
                    int w = i - left - 1;
                    int count = h * w;
                    sum += count;
                }
            }
        }

        stack.push(i);
    }
    return sum;
}
双指针法
public int trap(int[] height) {
    int len = height.length;
    if (len <= 2) {
        return 0;
    }
    int[] maxLeft = new int[len];
    int[] maxRight = new int[len];

    maxLeft[0] = height[0];
    for (int i = 1; i < len; i++) {
        maxLeft[i] = Math.max(height[i], maxLeft[i - 1]);
    }
    maxRight[len - 1] = height[len - 1];
    for (int i = len - 2; i >= 0; i--) {
        maxRight[i] = Math.max(height[i], maxRight[i + 1]);
    }
    int sum = 0;
    for (int i = 0; i < len; i++) {
        int count = Math.min(maxLeft[i], maxRight[i]) - height[i];
        if (count > 0) {
            sum += count;
        }
    }
    return sum;
}

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