503. 下一个更大元素 II
https://leetcode.cn/problems/next-greater-element-ii/
循环直接查两遍即可循环。
class Solution {
public int[] nextGreaterElements(int[] nums) {
int[] answer=new int[nums.length];
Deque<Integer> stack=new LinkedList<>();
Arrays.fill(answer,-1);
for(int i=0;i<nums.length*2;i++){
while(!stack.isEmpty()&&nums[i%nums.length]>nums[stack.peek()]){
answer[stack.peek()]=nums[i%nums.length];
stack.pop();
}
stack.push(i%nums.length);
}
return answer;
}
}
42. 接雨水
https://leetcode.cn/problems/trapping-rain-water/
尝试根据两端的下标差和height计算但是没写出来。
每列的计算=min(左边最大高度,右边最大高度)-当列高度。
class Solution {
public int trap(int[] height) {
int n=height.length;
if(n<3) return 0;
int[] maxLeft = new int[n];
int[] maxRight = new int[n];
maxLeft[0] = height[0];
for (int i = 1; i< n; i++) maxLeft[i] = Math.max(height[i], maxLeft[i-1]);
maxRight[n-1] = height[n-1];
for (int i = n-2; i>=0; i--) maxRight[i] = Math.max(height[i], maxRight[i+1]);
int res=0;
for (int i = 1; i< n; i++){
if (Math.min(maxLeft[i], maxRight[i]) > height[i]) res += Math.min(maxLeft[i], maxRight[i]) - height[i];
}
return res;
}
}
单调栈方法
情况一:当前遍历的元素(柱子)高度小于栈顶元素的高度 height[i] < height[st.top()]
情况二:当前遍历的元素(柱子)高度等于栈顶元素的高度 height[i] == height[st.top()]
情况三:当前遍历的元素(柱子)高度大于栈顶元素的高度 height[i] > height[st.top()]
>栈顶是,栈顶元素便是中间元素,凹部分,左右是高的部分,便可以计算雨水。
res+=(i-stack.peek()-1)*(Math.min(height[i],height[stack.peek()])-height[mid]);
class Solution {
public int trap(int[] height) {
int n=height.length;
Deque<Integer> stack=new LinkedList<>();
stack.push(0);
int res=0;
for (int i = 1; i< n; i++){
while(!stack.isEmpty()&&height[i]>height[stack.peek()]){
int mid = stack.pop();
if (!stack.isEmpty()){
res+=(i-stack.peek()-1)*(Math.min(height[i],height[stack.peek()])-height[mid]);
}
}
stack.push(i);
}
return res;
}
}