leetcode- 42. 接雨水

中间低,两边高才有雨水,想到单减栈
cur>=height[top]低:push
cur<height[top]:此时站内应至少有两个元素才能形成坑
class Solution {
	public int trap(int[] height) {
		Stack<Integer> stack = new Stack<>();
		int i = 0, res = 0;
		while (i < height.length) {
			if (stack.isEmpty() || height[i] <= height[stack.peek()]) {
				stack.push(i++);
			} else {// 栈至少有两个元素
				int top = stack.pop();
				if (stack.isEmpty())
					continue;
				res += (Math.min(height[stack.peek()], height[i]) - height[top]) * (i - stack.peek() - 1);
			}
		}
		return res;
	}
}

猜你喜欢

转载自blog.csdn.net/qq_39370495/article/details/89427954