Leetcode 42. Trapping Rain Water

Source: Internet
Author: User

https://leetcode.com/articles/trapping-rain-water/

Finish a hard difficulty of the topic, the individual is very excited, suddenly that feel "double pointer" is simply an artifact, the title requirements of the entire container can be filled with the amount of water, intuitively, only the groove part can be filled with water, violent search method is too high complexity, the best way is to use a double pointer, left and right to place one, Notice how much of the water is shorter that side of the decision, if the left height is less than the right, then continue to check whether the left height is greater than or equal to Left_max, if it is updated Left_max, otherwise accumulated water;

The code is as follows

1 classSolution {2  Public:3     intTrap (vector<int>&height) {4         //Self According to the official answer pseudo code complete5         intLen =height.size ();6         intleft =0, right = Len-1;7         //int ans = 0, Left_max = height[left], Right_max = height[right];8         intAns =0, Left_max =0, Right_max =0;//here the Mgax is initialized to 0, otherwise it will go wrong, such as height is empty, the above code will access the subscript-1 element9          while(Left <Right )Ten         { One             if(Height[left] <Height[right]) A             { -                 if(Height[left] >=Left_max) -Left_max =Height[left]; the                 Else -Ans + = Left_max-Height[left]; -left++; -             } +             Else -             { +                 if(Height[right] >=Right_max) ARight_max =Height[right]; at                 Else -Ans + = Right_max-Height[right]; -right--; -             } -         } -         returnans; in     } -};

Time complexity: O (N)

Space complexity: O (1)

two brushes , 2018-03-14, missing update righ with left part

Leetcode 42. 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.