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

被折叠的 条评论
为什么被折叠?



