LeetCode 42 - Trapping Rain Water

来源:互联网 发布:有趣的c语言表白程序 编辑:程序博客网 时间:2024/05/19 12:12

Trapping Rain Water

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is 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 rain water (blue section) are being trapped. Thanks Marcos for contributing this image!

My Two Pass Code

class Solution {public:    int trap(vector<int>& height) {        int size = height.size();        int start = 0, end = size - 1;        int total = 0;        // Left to right        for (int i = 1; i < size; i++)        {            if (height[i] >= height[start])            {                if (i == start + 1)                    start= i;                else                {                    end = i;                    // Caculate                    int s = min(height[start], height[end]) * (end - start - 1);                    cout << start << " " << end << " " << s << endl;                    for (int j = start + 1; j < end; j++)                        s -= height[j];                    total += s;                    start = end;                }            }        }        // Right to left        start = size - 1, end = 0;        for (int i = size - 2; i >= 0; i--)        {            if (height[i] > height[start])            {                if (i == start - 1)                    start= i;                else                {                    end = i;                    // Caculate                    int s = min(height[start], height[end]) * (start - end - 1);                    for (int j = start - 1; j > end; j--)                        s -= height[j];                    total += s;                    start = end;                }            }        }        return total;    }};

Runtime: 20 ms


My One Pass Code

class Solution {public:    int trap(vector<int>& height) {        int size = height.size();        int start = 0, end = size - 1;        int max_left_height = 0, max_right_height = 0;        int total = 0;        while (start <= end)        {            if (height[start] <= height[end])            {                if (height[start] <= max_left_height)                    total += max_left_height - height[start];                else                    max_left_height = height[start];                start++;            }            else            {                if (height[end] <= max_right_height)                    total += max_right_height - height[end];                else                    max_right_height = height[end];                end--;            }        }        return total;    }};
Runtime: 8 ms

0 0
原创粉丝点击