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