Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

42. Trapping Rain Water #96

Open
Tcdian opened this issue Apr 4, 2020 · 1 comment
Open

42. Trapping Rain Water #96

Tcdian opened this issue Apr 4, 2020 · 1 comment

Comments

@Tcdian
Copy link
Owner

Tcdian commented Apr 4, 2020

42. Trapping Rain Water

给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。

上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接 6 个单位的雨水(蓝色部分表示雨水)。

Example

Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
@Tcdian
Copy link
Owner Author

Tcdian commented Apr 4, 2020

Solution ( Two Pointers )

  • JavaScript Solution
/**
 * @param {number[]} height
 * @return {number}
 */
var trap = function(height) {
    let result = 0;
    let left = 0;
    let right = height.length - 1;
    let leftMaxHeight = 0;
    let rightMaxHeight = 0;

    while (left < right) {
        const leftHeight = height[left];
        const rightHeight = height[right];
        if (leftHeight < rightHeight) {
            if (leftHeight < leftMaxHeight) {
                result += leftMaxHeight - leftHeight;
            } else {
                leftMaxHeight = leftHeight;
            }
            left++;
        } else {
            if (rightHeight < rightMaxHeight) {
                result += rightMaxHeight - rightHeight;
            } else {
                rightMaxHeight = rightHeight;
            }
            right--;
        }
    }
    
    return result;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant