503. 下一个更大元素 II
这里很巧妙的运用了一个技巧,那就是使用了双倍的长度,让这个数组长度乘以二,然后从表象上制造一种循环的错觉,代码如下:
public int[] nextGreaterElements(int[] nums) {
int[] re = new int[nums.length];
Arrays.fill(re,-1);
Stack<Integer> st = new Stack();
int size = nums.length;
st.push(0);
for(int i=1;i<size*2;i++){
while(!st.empty() && nums[i % size] > nums[st.peek()]) {
re[st.peek()] = nums[i % size];//更新result
st.pop();//弹出栈顶
}
st.push(i % size);
}
return re;
}
42. 接雨水
这里用到单调栈的技巧请务必记牢,计算过程大致为,先将栈顶元素取出,然后将用当前元素和目前栈顶元素的最小值减去取出的元素为高,然后用栈顶元素的坐标减去当前元素的坐标为宽进行计算,代码如下:
public int trap(int[] height) {
Stack<Integer> st = new Stack();
st.push(0);
int re = 0;
int w = 0;
int h = 0;
int tool;
for(int i=0;i<height.length;i++){
if(height[i]<=height[st.peek()])st.push(i);
else{
while(!st.isEmpty()&&height[i]>height[st.peek()]){
tool = st.pop();
if(!st.isEmpty()){
h = Math.min(height[st.peek()],height[i])-height[tool];
w = i-st.peek()-1;
re+=h*w;
}
}
st.push(i);
}
}
return re;
}