【代码随想录训练营】【Day59】第十章|单调栈|503.下一个更大元素II|42.接雨水

下一个更大元素II

题目详细:LeetCode.503

详细的题解可查阅:《代码随想录》— 下一个更大元素II

Java解法(单调栈):

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

接雨水

题目详细:LeetCode.42

详细的题解可查阅:《代码随想录》— 接雨水

Java解法(单调栈):

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

你可能感兴趣的:(代码随想录训练营,leetcode,算法,职场和发展)