503. 下一个更大元素 II
class Solution {
public int[] nextGreaterElements(int[] nums) {
if(nums == null || nums.length <= 1){
return new int[]{-1};
}
Stack<Integer> monoStack = new Stack<>();
int[] res = new int[nums.length];
Arrays.fill(res, -1);
for(int i = 0; i < nums.length * 2; i++){
while(!monoStack.isEmpty() && nums[monoStack.peek()] < nums[i % nums.length]){
res[monoStack.pop()] = nums[i % nums.length];
}
monoStack.push(i % nums.length);
}
return res;
}
}
42. 接雨水
双指针法:
class Solution {
public int trap(int[] height) {
int n = height.length;
int[] leftMax = new int[n];
int[] rightMax = new int[n];
int leftHighest = 0;
for(int i = 0; i < n; i++){
leftMax[i] = leftHighest;
leftHighest = Math.max(leftHighest, height[i]);
}
int rightHeighest = 0;
for(int i = n - 1; i >= 0; i--){
rightMax[i] = rightHeighest;
rightHeighest = Math.max(rightHeighest, height[i]);
}
int res = 0;
for(int i = 0; i < n; i++){
int minHeight = Math.min(leftMax[i], rightMax[i]);
if(minHeight > height[i]){
res += minHeight - height[i];
}
}
return res;
}
}
单调栈法:
class Solution {
public int trap(int[] height) {
Stack<Integer> monoStack = new Stack<>();
int res = 0;
for(int i = 0; i < height.length; i++){
while(!monoStack.isEmpty() && height[monoStack.peek()] < height[i]){
int mid = monoStack.pop();
if(!monoStack.isEmpty()){
int h = Math.min(height[monoStack.peek()], height[i]) - height[mid];
int w = i - monoStack.peek() - 1;
res += h * w;
}
}
monoStack.push(i);
}
return res;
}
}