数组——container-with-most-water和trapping-rain-water

本文解析了两个经典的算法问题:求容器能盛的最大水量及计算降雨后能积存的雨水量。通过双指针技巧解决盛水量问题,并介绍了一种高效的方法来计算雨后积水总量。

container-with-most-water

题意是有个高度数组,就相当于隔板的高度,求数组中任意两隔板间盛水的最大量。隔板间的距离与较低隔板的高度乘积即为盛水的容量。

在数组heght[n]中两点left,right,求最大的 Math.abs(right-left)*Math.min(height[left],height[right])。

public class Solution {
    public int maxArea(int[] height) {
        if(height == null||height.length<2)
            return 0;
        int maxarea=0;
        int left=0;
        int right=height.length-1;
        while(left<right)
            {
            int cur=Math.abs(left-right)*Math.min(height[left],height[right]);
            if(cur>maxarea)
                {
                maxarea=cur;
            }
            if(height[left]<height[right])
                {
                left++;
            }else
                {
                right--;
            }
        }
       return maxarea;
    }
}




trapping-rain-water


Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

For example, 
Given[0,1,0,2,1,0,1,3,2,1,2,1], return6.

The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!

先遍历一遍找到塔顶,然后分别从两边开始,往塔顶所在位置遍历,水位只会增高不会减小,且一直和最近遇到的最大高度持平,这样知道了实时水位,就可以边遍历边计算面积。

public class Solution {
    public int trap(int[] nums) {
        if(nums == null||nums.length < 3)
            return 0;
        //找到最大的nums[i],再分别从两边像其靠拢计算
        int max=0;
        int maxid=0;
        for(int i=0;i<nums.length;i++)
            {
            if(nums[i]>max)
                {
                max=nums[i];
                maxid=i;
            }
        }
        int area=0;
        int height=0;
        //计算maxid左边水的总面积
        for(int i=0;i<maxid;i++)
            {
            if(nums[i]>=height)
                {
                height=nums[i];
            }else
                {
                area+=height-nums[i];
            }
        }
        //计算maxid右边水的总面积
        height=0;
        for(int j=nums.length-1;j>maxid;j--)
            {
            if(nums[j]>=height)
                {
                height=nums[j];
            }else
                {
                area+=height-nums[j];
            }
        }
        return area;
    }
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值