● 503.下一个更大元素II Next Greater Element II - LeetCode
class Solution {
public int[] nextGreaterElements(int[] nums) {
int[] res = new int[nums.length];
Arrays.fill(res, -1);
if (nums.length == 0) return res;
Stack<Integer> stack = new Stack<>();
stack.push(0);
for (int i = 1; i < nums.length * 2; i++) {
if (nums[i % nums.length] < nums[stack.peek()]) {
stack.push(i % nums.length);
} else if(nums[i % nums.length] == nums[stack.peek()]) {
stack.push(i % nums.length);
} else {
while (!stack.isEmpty() && nums[i % nums.length] > nums[stack.peek()]) {
res[stack.peek()] = nums[i % nums.length];
stack.pop();
}
stack.push(i % nums.length);
}
}
return res;
}
}
● 42. 接雨水 Trapping Rain Water - LeetCode
stack<>
stack.push(0)
for (int i = 1; i < height; i++)
if (h[i] < h[
感觉这题的单调栈做法没弄懂
class Solution {
public int trap(int[] height){
int size = height.length;
if (size <= 2) return 0;
// in the stack, we push the index of array
// using height[] to access the real height
Stack<Integer> stack = new Stack<Integer>();
stack.push(0);
int sum = 0;
for (int index = 1; index < size; index++){
int stackTop = stack.peek();
if (height[index] < height[stackTop]){
stack.push(index);
}else if (height[index] == height[stackTop]){
// 因为相等的相邻墙,左边一个是不可能存放雨水的,所以pop左边的index, push当前的index
stack.pop();
stack.push(index);
}else{
//pop up all lower value
int heightAtIdx = height[index];
while (!stack.isEmpty() && (heightAtIdx > height[stackTop])){
int mid = stack.pop();
if (!stack.isEmpty()){
int left = stack.peek();
int h = Math.min(height[left], height[index]) - height[mid];
int w = index - left - 1;
int hold = h * w;
if (hold > 0) sum += hold;
stackTop = stack.peek();
}
}
stack.push(index);
}
}
return sum;
}
}
双指针更好理解
class Solution {
public int trap(int[] height) {
int left = 0;
int right = height.length - 1;
int leftMax = 0;
int rightMax = 0;
int res = 0;
while (left < right) {
leftMax = Math.max(leftMax, height[left]);
rightMax = Math.max(rightMax, height[right]);
if (leftMax < rightMax) {
res += leftMax - height[left];
left++;
} else {
res += rightMax - height[right];
right--;
}
}
return res;
}
}