Leecode 42. 接雨水

简介: Leecode 42. 接雨水

题目描述:

解题思想:这个题我们可以利用局部性最佳原理,将整个数组从最左边和最右边同时比较开始,

  • 在左半区内,水量为左边局部最大-当前深度,比如在题目给出的测试用例中
    1-0 = 1,2-1=1,2-0=2,2-1=1
  • 在右半区内,水量为右边局部最大-当前深度,比如在题目给出的测试用例中
    2-1=1
    所以测试用例总共可以接的雨水就是1 + 1 + 2 + 1 + 1 = 6
class Solution {
    public int trap(int[] height) {
        if(height.length<=1)return 0;
        int res=0;
        int left=0;
        int right=height.length-1;
        int lmax=height[left];
        int rmax=height[right];
        //假设成山状态,中间最大值,
        while(left<right){
            if(height[left]<height[right]){
                //左半区,水量=左边局部最大-当前深度
                if(height[left]>=lmax)
                    lmax=height[left];
                else
                    res+=lmax-height[left];
                left++;
            }else{
                //右半区同理
                if(height[right]>=rmax)
                    rmax=height[right];
                else    
                    res+=rmax-height[right];
                right--;
            }
        }
        return res;
    }
}


相关文章
|
1月前
|
容器
leetcode-407:接雨水 II
leetcode-407:接雨水 II
46 0
|
1月前
|
图计算 索引
leetcode-42:接雨水
leetcode-42:接雨水
35 0
|
8月前
|
算法 测试技术 图计算
|
1月前
|
容器
每日一题——接雨水(单调栈)
每日一题——接雨水(单调栈)
|
1月前
|
图计算
【每日一题Day274】LC42接雨水 | 单调栈
【每日一题Day274】LC42接雨水 | 单调栈
30 0
|
7月前
|
算法
【LeetCode力扣】42. 接雨水
【LeetCode力扣】42. 接雨水
44 0
|
10月前
|
机器学习/深度学习 人工智能 移动开发
Acwing 1574. 接雨水
Acwing 1574. 接雨水
45 0
|
11月前
|
容器 Cloud Native
【刷题日记】42. 接雨水
本次刷题日记的第 14 篇,力扣题为:42. 接雨水 ,困难
|
存储 算法
407. 接雨水 II : 经典 Dijkstra 运用题
407. 接雨水 II : 经典 Dijkstra 运用题
|
算法 图计算 C++
每日算法系列【LeetCode 42】接雨水
每日算法系列【LeetCode 42】接雨水