[Leetcode] Trapping Rain Water

Source: Internet
Author: User

Given n non-negative integers representing an elevation map where the width of each bar are 1, compute how much WA ter It is the able to trap after raining.

For example,
given[0,1,0,2,1,0,1,3,2,1,2,1], return6.

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 the Rain Water (blue section) is being trapped. Thanks Marcos for contributing this image!

https://oj.leetcode.com/problems/trapping-rain-water/

Idea 1: For a certain value a[i], the maximum amount of water that can be installed depends on the highest value before I leftmaxt[i] and the highest rightmax[i on the right of I], the volume of Water is min (left,right) –a[i]. : In order to calculate the height, the first pass computes the array leftmaxt from left to right, and the second time calculates the Rightmax from right to left. Space-time complexity is O (n).

Train of thought 2: The improvement idea 1, can use the constant space to fix. Specific ideas, first find the highest bar, and then the total on both sides of the calculation, Edge Computing edge update curheight.

For details, refer to this

Idea 1:

public class Solution {public int trap (int[] a) {if (a = = NULL | | A.length < 3) return 0;int n = a.length;int[] Leftmax = new int[n];int[] Rightmax = new Int[n];int i;int max = a[0];for (i = 1; i < n-1; i++) {Leftmax[i] = max;if (A[i] > max) max = a[i];} max = a[n-1];for (i = n-2; i > 0; i--) {Rightmax[i] = max;if (A[i] > max) max = a[i];} int count = 0;for (i = 1; i < n-1; i++) {int min = Leftmax[i] < Rightmax[i]? Leftmax[i]: rightmax[i];if (min ; A[i]) Count + = Min-a[i];} return count;}  public static void Main (string[] args) {System.out.println (New solution (). Trap (new int[] {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1}));}}

Reference:

Http://fisherlei.blogspot.com/2013/01/leetcode-trapping-rain-water.html

Http://www.cnblogs.com/lichen782/p/Leetcode_Trapping_Rain_Water.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.