原题链接在这里:https://leetcode.com/problems/trapping-rain-water/
题目:
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!
Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1] Output: 6
题解:
Two Pointers, l and r. 移动指向高度小的, 因为小的这边围住的水肯定能被大的那一边围住.
然后更新这个方向的最大高度,用新的最大高度 减掉 当前高度 就是这一位置能围住的水量.
Time Complexity: O(n), n = height.length. Space: O(1).
AC Java:
1 public class Solution { 2 public int trap(int[] height) { 3 if(height == null || height.length < 3){ 4 return 0; 5 } 6 7 int l = 0; 8 int r = height.length-1; 9 int leftHeight = height[l]; 10 int rightHeight = height[r]; 11 int res = 0; 12 while(l < r){ 13 if(leftHeight < rightHeight){ 14 l++; 15 leftHeight = Math.max(leftHeight, height[l]); 16 res += leftHeight - height[l]; 17 }else{ 18 r--; 19 rightHeight = Math.max(rightHeight, height[r]); 20 res += rightHeight - height[r]; 21 } 22 } 23 return res; 24 } 25 }
跟上Trapping Rain Water II, Pour Water, Container With Most Water.