503.下一个更大元素II
class Solution {
public int[] nextGreaterElements(int[] nums) {
int[] res = new int[nums.length];
Arrays.fill(res, -1);
Stack<Integer> st =new Stack<>();
for(int i=0;i<nums.length * 2;i++){
while(!st.empty() && nums[i % nums.length] > nums[st.peek()]) {
res[st.peek()] = nums[i % nums.length];//更新result
st.pop();//弹出栈顶
}
st.push(i % nums.length);
}
return res;
}
}
42. 接雨水
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{
while(!st.isEmpty() && height[i] > height[st.peek()]){
int mid = st.pop();
if(!st.isEmpty()){
int h = Math.min(height[i], height[st.peek()]) - height[mid];
int w = i-st.peek()-1;
sum += h*w;
}
}
st.push(i);
}
}
return sum;
}
}