java 42.诱捕雨水(#)。java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 42.诱捕雨水(#)。java相关的知识,希望对你有一定的参考价值。

public class Solution {

    public int trap(int[] height) {
        int res = 0, l = 0, r = height.length - 1, high = 0, low = 0;
        while (l < r) {
            low = height[l] < height[r] ? height[l++] : height[r--];
            high = Math.max(high, low);
            res += high - low;
        }
        return res;
    }
}
public class Solution {

    public int trap(int[] height) {
    if (height.length < 3) return 0;
    
    int ans = 0;
    int l = 0, r = height.length - 1;
    
    // find the left and right edge which can hold water
    while (l < r && height[l] <= height[l + 1]) l++;
    while (l < r && height[r] <= height[r - 1]) r--;
    
    while (l < r) {
        int left = height[l];
        int right = height[r];
        if (left <= right) {
            // add volum until an edge larger than the left edge
            while (l < r && left >= height[++l]) {
                ans += left - height[l];
            }
        } else {
            // add volum until an edge larger than the right volum
            while (l < r && height[--r] <= right) {
                ans += right - height[r];
            }
        }
    }
    return ans;
}
}

以上是关于java 42.诱捕雨水(#)。java的主要内容,如果未能解决你的问题,请参考以下文章

java 42.诱捕雨水(#)。java

java 42.诱捕雨水(#)。java

java 42.诱捕雨水(#)。java

java 42.诱捕雨水(#)。java

java Leetcode - 诱捕雨水收集雨水

java刷题--42接雨水