《LeetCode力扣练习》代码随想录——单调栈(接雨水—Java)
刷题思路来源于 代码随想录
42. 接雨水
-
单调栈
class Solution { public int trap(int[] height) { if (height.length < 3) { return 0; } Deque<Integer> stack = new ArrayDeque<>(); stack.push(0); int result = 0; for (int i = 1; i < height.length; i++) { if (height[i] < height[stack.peek()]) { stack.push(i); } else if (height[i] == height[stack.peek()]) { stack.pop(); stack.push(i); } else { while (!stack.isEmpty() && height[i] > height[stack.peek()]) { int low = height[stack.pop()]; if (!stack.isEmpty()) { int high = Math.min(height[i], height[stack.peek()]); result += (i - stack.peek() - 1) * (high - low); } } stack.push(i); } } return result; } }