[LeetCode练习]42.接雨水

[LeetCode练习]42.接雨水_第1张图片

先记录一下答案:

解题思路:

双指针,一个从左往右,一个从右往左,两边分别记录一个最高值

先比较左右指针的值,左边大右走,右边走左走

这样可以保证走的那一方一定会遇到桶的另一边

如果新柱子比当前最高值大,则更新最高值,指针继续往中间走

如果新柱子比当前最高值小,则两数之差为两根柱子能存的水,然后指针继续往中间走

public int trapRainWater2(int[] heights) {
    
    int left = 0, right = heights.length - 1;
    int res = 0;
    if(left >= right) {
        return res;
    }
    int leftheight = heights[left];
    int rightheight = heights[right];
    while(left < right) {
        if(leftheight < rightheight) {
            left ++;
            if(leftheight > heights[left]) {
                res += (leftheight - heights[left]);
            } else {
                leftheight = heights[left];
            }
        } else {
            right --;
            if(rightheight > heights[right]) {
                res += (rightheight - heights[right]);
            } else {
                rightheight = heights[right];
            }
        }
    }
    return res;
}

 

你可能感兴趣的:(LeetCode)