Leetcode042:trapping Rain Water

Source: Internet
Author: User

Problem description
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 analysis This topic solution thinking can refer to Leetcode011:container with the most water analysis, leetcode011 is to find the largest area of the surrounding, there are differences, statistics "water" area, or from both sides to the middle scan, time complexity O (n )。 Here to set a water level h, indicating the height of the current circumference, if the subsequent sweep surface to the lower than H, the description can be filled, statistics; if higher than H, update H.
Code
Run Time: 13msclass solution {public:int Trap (vector<int>& height) {int i = 0, j = height.size () -1;int ans = 0;int h = 0;while (j-i >= 0) {if (Height[i] > Height[j]) {if (Height[j] <= h) {ans + = (h-height[j]);} else{h = Height[j];} j--;} else if (Height[i] < height[j]) {if (Height[i] <= h) {ans + = (h-height[i]); i++;} else{h = Height[i];}} Else{if (Height[i] <= h) {if (i! = j) ans + = 2 * (H-height[i]); Elseans + = (H-height[i]);} else{h = Height[i];} i++; j--;}} return ans;};


Leetcode042: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.