题目1:【二刷完成】
class Solution {
public int[] nextGreaterElements(int[] nums) {
//边界判断
if(nums == null || nums.length <= 1) {
return new int[]{-1};
}
int size = nums.length;
int[] result = new int[size];//存放结果
Arrays.fill(result,-1);//默认全部初始化为-1
Stack<Integer> st= new Stack<>();//栈中存放的是nums中的元素下标
for(int i = 0; i < 2*size; i++) {
//取模的过程遍历数组
while(!st.empty() && nums[i % size] > nums[st.peek()]) {
result[st.peek()] = nums[i % size];//更新result
st.pop();//弹出栈顶
}
st.push(i % size);
}
return result;
}
}
题目2:【二刷完成】
class Solution {
public int trap(int[] height) {
//单调栈方法
int sum = 0;
int len = height.length;
Stack<Integer> st = new Stack<Integer>();
st.push(0);
for (int i=1;i<len;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;
int area = h*w;
if (area>0) sum += area;
}
}
st.push(i);
}
}
return sum;
}
}