代码随想录训练营 Day59
今日任务
503.下一个更大元素Ⅱ
42.接雨水
语言:Java
503. 下一个更大元素Ⅱ
链接:https://leetcode.cn/problems/next-greater-element-ii/
class Solution {
public int[] nextGreaterElements(int[] nums) {
int[] result = new int[nums.length];
for(int i = 0; i < result.length; i++){
result[i] = -1;
}
Stack<Integer> st = new Stack<>();
st.push(0);
for(int i = 1; i < 2 * nums.length; i++){
if(nums[i % nums.length] <= nums[st.peek()]){
st.push(i % nums.length);
}
else{
while(!st.isEmpty() && nums[i % nums.length] > nums[st.peek()]){
result[st.pop()] = nums[i % nums.length];
}
st.push(i % nums.length);
}
}
return result;
}
}
42. 接雨水
链接:https://leetcode.cn/problems/trapping-rain-water/
双指针
要明确是按行还是按列计算的雨水容量
class Solution {
public int trap(int[] height) {
int sum = 0;
for(int i = 1; i < height.length - 1; i++){
int lHeight = height[i];
int rHeight = height[i];
for(int j = i - 1; j >= 0; j--){
if(height[j] > lHeight){
lHeight = height[j];
}
}
for(int j = i + 1; j < height.length; j++){
if(height[j] > rHeight){
rHeight = height[j];
}
}
int cur = Math.min(lHeight, rHeight) - height[i];
sum += cur;
}
return sum;
}
}
动态规划
class Solution {
public int trap(int[] height) {
int sum = 0;
int[] lHeight = new int[height.length];
lHeight[0] = height[0];
int[] rHeight = new int[height.length];
rHeight[height.length - 1] = height[height.length - 1];
for(int i = 1; i < height.length - 1; i++){
lHeight[i] = Math.max(lHeight[i - 1], height[i]);
}
for(int i = height.length - 2; i >= 0; i--){
rHeight[i] = Math.max(rHeight[i + 1], height[i]);
}
for(int i = 1; i < height.length - 1; i++){
sum += Math.min(lHeight[i], rHeight[i]) - height[i];
}
return sum;
}
}
单调栈
相当于按行计算雨水容量
class Solution {
public int trap(int[] height) {
int sum = 0;
Stack<Integer> st = new Stack<>();
st.push(0);
for(int i = 1; i < height.length; i++){
if(height[i] < height[st.peek()]){
st.push(i);
}
else if(height[i] == height[st.peek()]){
st.pop();
st.push(i);
}
else if(height[i] > height[st.peek()]){
while(!st.isEmpty() && height[i] > height[st.peek()]){
int height1 = i;
int bottom = st.pop();
if(!st.isEmpty()){
int height2 = st.peek();
sum += (Math.min(height[height1], height[height2]) - height[bottom]) * (height1 - height2 - 1);
}
}
st.push(i);
}
}
return sum;
}
}