LeetCode 42. Trapping Rain Water_

Given  n  non-negative integers representing the height map of each column with a width of 1, calculate how much rain the column can receive after it rains.

Above is the heightmap represented by the array [0,1,0,2,1,0,1,3,2,1,2,1], in this case 6 units of rain can be picked up (blue part indicates rain). Thanks to Marcos for  contributing this image.

Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6

        public int trap(int[] height) {
		int ans = 0;
		if (height.length < 3)
			return ans;
		// 最高的索引
		int maxIndex = 0;
		// 最高的高度
		int maxValue = height[0];

		for (int i = 0; i < height.length; i++) {
			if (height[i] >= maxValue) {
				maxIndex = i;
				maxValue = height[i];
			}
		}
		
		// 从左边到i最高的高度
		int partMax = height[0];
		for (int i = 0; i < maxIndex; i++) {
			if (height[i] > partMax)
				partMax = height[i];
			else
				ans += partMax - height[i];
		}
		
		// 从右边到i最高的高度
		partMax = height[height.length - 1];
		for (int i = height.length - 1; i > maxIndex; i--) {
			if (height[i] > partMax)
				partMax = height[i];
			else
				ans += partMax - height[i];
		}

		return ans;
	}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326140916&siteId=291194637