503. 下一个更大元素 II
42. 接雨水
- 下一个更大元素 II
class Solution {
public int[] nextGreaterElements(int[] nums) {
int len = nums.length;
if(len<=1) return new int[]{-1};
int[] res = new int[len];
Stack<Integer> stack = new Stack();
stack.push(0);
Arrays.fill(res,-1);
for(int i=1;i<2*len;i++){
while(!stack.isEmpty() && nums[i%len] > nums[stack.peek()]){
res[stack.peek()] = nums[i % len];
stack.pop();
}
stack.push(i%len);
}
return res;
}
}
- 接雨水
class Solution {
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-1;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 tmp = Math.min(maxLeft[i],maxRight[i]) - height[i];
if(tmp > 0) sum += tmp;
}
return sum;
}
}