[Leetcode] Trapping Rain Water

Source: Internet
Author: User

Trapping Rain Water

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] , return 6 .


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!

Problem Solving Ideas:

1, my method: The thought of the two sides of the clip, if the left side is less than the right, then move the left hand, otherwise move the pointer to the right. At the same time, if the moving pointer is less than the previous minimum height, the capacity minus the height that the move pointer refers to at this point. If both the moving pointer and the non-moving pointer are greater than the previous minimum height, the excess is added. Don't understand, the code is better understood:

Class Solution {Public:int trap (vector<int>& height) {int len = height.size (), if (len<3) {return 0;} int start = 0, end = Len-1;int result = 0, MinH = 0;minh = Min (Height[start], height[end]); result = MinH * (end-start -1); while (start<end-1) {if (Height[start]
2, online Another good way is left and right side sweep method. Record the maximum number of left and right of each number. The left largest and the right largest constitute a container, which subtracts itself from the space, which corresponds to the steps of this position contributed capacity.

Class Solution {Public:int trap (vector<int>& height) {int len = height.size (), if (len<3) {return 0;} int Maxl[len], maxr[len];int maxh = height[0];maxl[0] = 0;for (int i=1; i<len; i++) {    maxl[i] = maxh;    MAXH = Max (Maxh, Height[i]);} Maxh = height[len-1];maxr[len-1]=0;int result=0;for (int i=len-2; i>=0; i--) {    maxr[i]=maxh;    MAXH = Max (Maxh, Height[i]);        Result +=max (0, Min (maxl[i], maxr[i])-height[i]);} return result;};


[Leetcode] Trapping Rain Water

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.