代码随想录算法训练营20期|第六十二天|单调栈part02|● 503.下一个更大元素II ● 42. 接雨水

  •  503.下一个更大元素II 
class Solution {
    public int[] nextGreaterElements(int[] nums) {
        if (nums == null || nums.length <= 1) {
            return new int[]{-1};
        }
        int size = nums.length;
        int[] res = new int[size];
        Arrays.fill(res, -1);
        Stack stack = new Stack<>();
        for (int i = 0; i < 2 * size; i++) {
            while (!stack.isEmpty() && nums[i % size] > nums[stack.peek()]) {
                res[stack.peek()] = nums[i % size];
                stack.pop();
            }
            stack.push(i % size);
        }
        return res;
    }
}
  •  42. 接雨水  
class Solution {
    public int trap(int[] height) {
        int left = 0;
        int right = height.length - 1;
        int leftMax = 0;
        int rightMax = 0;
        int res = 0;

        while (left < right) {
             leftMax = Math.max(leftMax, height[left]);
             rightMax = Math.max(rightMax, height[right]);

             if (leftMax < rightMax) {
                 res += leftMax - height[left];
                 left++;
             } else {
                 res += rightMax - height[right];
                 right--;
             }
        }
        return res;
    }
}

你可能感兴趣的:(代码随想录二刷,算法,java,数据结构)