Leetcode-trapping Rain Water Solution

Source: Internet
Author: User



Solution: (1) Set up a two-dimensional array, record the left highest point of each position and the right highest point, can be calculated by O (n).

(2) According to the above information and the current height, calculate the vertical direction of the point can hold how much water, still O (n) completed.

In the synthesis, the asymptotic time complexity is O (n);


Class Solution {
Public
int trap (int a[], int n) {
if (n<=0)
return 0;
int* High=new int[n*2];
high[0*2+0]=0;
for (int i=1;i<n;i++) {
if (a[i-1]>high[(i-1) *2+0])
HIGH[I*2+0]=A[I-1];
Else
high[i*2+0]=high[(i-1) *2+0];
}
high[(n-1) *2+1]=0;
for (int i=n-2;i>=0;i--) {
if (a[i+1]>high[(i+1) *2+1])
HIGH[I*2+1]=A[I+1];
Else
high[i*2+1]=high[(i+1) *2+1];
}
int sum=0;
for (int i=0;i<n;i++) {
int tmp=high[i*2+0]>high[i*2+1]?high[i*2+1]:high[i*2+0];
Tmp=tmp-a[i];
if (tmp<0)
Tmp=0;
sum+=tmp;
}
Delete[] High;
return sum;
}
};


Leetcode-trapping Rain Water Solution

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.