题解 | 接雨水问题

接雨水问题

https://www.nowcoder.com/practice/31c1aed01b394f0b8b7734de0324e00f

import java.util.*;


public class Solution {
    /**
     * 两边就像是两堵墙,能存多少水有较矮的那堵墙决定,高的强起到的作用就是挡水的作用
     * 维护两个指针,同时维护两个最大值,左边和右边的最大值,
     * 如果右边最大值比左边最大值大,左边往右走,同时计算左边最大值,左边最大值与左边当前值的差就是当前位置能存多少水
     * 如果左边最大值比右边最大值大,右边往左走,同时计算右边最大值,右边最大值与右边当前值的差就是当前位置能存多少水
     *
     * @param arr
     * @return
     */
    public long maxWater(int[] arr) {
        if (arr == null || arr.length <= 2) {
            return 0L;
        }
        int left = 0;
        int right = arr.length - 1;
        int maxLeft = 0;
        int maxRight = 0;
        int area = 0;
        while (left < right) {
            maxLeft = Math.max(maxLeft, arr[left]);
            maxRight = Math.max(maxRight, arr[right]);
            if (maxLeft < maxRight) {
                area += maxLeft - arr[left];
                left++;
            } else {
                area += maxRight - arr[right];
                right--;
            }
        }
        return area;
    }
}

全部评论

相关推荐

03-01 21:45
中北大学 golang
孤蓝长空:请你说一下为什么你用websocket而不是http,请你说一下什么是rpc,为什么用rpc,你的rpc的传输协议是JSON,xml还是什么 请你描述一下你的鉴权流程(完整的) 我问的是第二个项目,随便问的哈哈哈
开工第一帖
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务