classSolution{ publicinttrap(int[] height){ Stack<Integer> stack = new Stack<>(); int res = 0, index = 0; while (index < height.length) { while (!stack.isEmpty() && height[stack.peek()]<height[index]) { int t = stack.pop(); if (stack.isEmpty()) break; int hi = Math.min(height[stack.peek()], height[index]) - height[t]; res += hi * (index-stack.peek()-1); } stack.push(index); index++; } return res; } }
方法二:动态规划
按列求雨水的高度。分别求出该列左右两侧的最高高度,两侧较低的值减去当前位置的高度即为雨水的高度。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution{ publicinttrap(int[] height){ int n = height.length; int[] left = newint[n]; int[] right = newint[n]; for (int i=1; i<n; i++) { left[i] = Math.max(height[i-1], left[i-1]); } for (int i=n-2; i>=0; i--) { right[i] = Math.max(height[i+1], right[i+1]); } int res = 0; for (int i=1; i<n-1; i++) { int h = Math.min(left[i], right[i]) - height[i]; if (h>0) res+=h; } return res; } }
classSolution{ publicintlargestRectangleArea(int[] heights){ int n = heights.length; // 在heights前后各插入一个0 int[] h = newint[n+2]; for (int i=1; i<n+1; i++) { h[i] = heights[i-1]; } n += 2; int res = 0; Stack<Integer> stack = new Stack<>(); stack.push(0);//避免判断栈是否为空 for (int i=1; i<n; i++) { while (h[stack.peek()]>h[i]) { int height = h[stack.pop()]; int width = i - stack.peek() - 1; int size = height * width; res = Math.max(res, size); } stack.push(i); } return res; } }
classSolution{ publicintmaximalRectangle(char[][] matrix){ int m = matrix.length; if (m==0) return0; int n = matrix[0].length; if (n==0) return0; int res = 0; int[] heights = newint[n+2]; for (int i=0; i<m; i++) { for (int j=0; j<n; j++) { heights[j+1] = matrix[i][j]=='0'? 0: heights[j+1] + 1; } res = Math.max(res, largestRectangleArea(heights)); } return res; }
publicintlargestRectangleArea(int[] heights){ int res = 0; Stack<Integer> stack = new Stack<>(); stack.push(0); for (int i=1; i<heights.length; i++) { while (heights[stack.peek()]>heights[i]) { int height = heights[stack.pop()]; int width = i - stack.peek() - 1; int size = height * width; res = Math.max(res, size); } stack.push(i); } return res; } }