leetcode刷题_接雨水

题目描述

此题比较简单!
在这里插入图片描述

Java解决方法

class Solution {
    
    
    public int trap(int[] height) {
    
    
        //每次取头或者尾中值小的方向向中间推进一格
        //计算当前格能盛水的体积或者更新头或者尾的最大值
        int sum = 0;
        int start = 0;
        int startValue = height[start];
        int end = height.length - 1;
        int endValue = height[end];
        while(start < end)
        {
    
    
            if(height[start] <= height[end])
            {
    
    
                start++;
                if(height[start] >= startValue)
                {
    
    
                    startValue = height[start];
                }
                else
                {
    
    
                    sum += startValue - height[start];
                }
            }
            else
            {
    
    
                end--;
                if(height[end] >= endValue)
                {
    
    
                    endValue = height[end];
                }
                else
                {
    
    
                    sum += endValue - height[end];
                }
            }
        }
        return sum;
    }
}

在这里插入图片描述

おすすめ

転載: blog.csdn.net/qq_42148307/article/details/120552968
おすすめ