503.下一个更大元素II
解法:代码随想录
题目:- LeetCode
就是比496. Next Greater Element I在结尾处多了一次循环。
class Solution {
public int[] nextGreaterElements(int[] nums) {
int[] res = new int[nums.length];
Arrays.fill(res, -1);
Stack<Integer> ms = new Stack();
boolean check = false;
for (int i = 0; i < nums.length; i++) {
while(ms.isEmpty() == false && nums[i] > nums[ms.peek()]) {
res[ms.pop()] = nums[i];
}
ms.push(i);
if (i == nums.length - 1 && check == false) {
i = -1;
check = true;
}
}
return res;
}
}
42. 接雨水
解法:代码随想录
题目:- LeetCode
1. 运用单调循环栈
2. 可得到左右两边比本柱长的柱子,然后两个柱子取最小
3. 和本柱子相减得到高度。
4. 左右两个柱子坐标相减得到宽度(需额外减一)
5.相乘得到面积,累加到sum里面。
class Solution {
public int trap(int[] height) {
int sum = 0;
Stack<Integer> ms = new Stack();
for (int i = 0; i < height.length; i++) {
while (ms.isEmpty() == false && height[i] >= height[ms.peek()]) {
int idx = ms.pop();
if (ms.isEmpty() == true) continue;
int h = Math.min(height[ms.peek()], height[i]) - height[idx];
int w = i - ms.peek() - 1;
sum += h * w;
}
ms.push(i);
}
return sum;
}
}