题目:
给定n个非负整数a1 a2…,其中每个点表示坐标(i, ai)处的一个点。画出两条垂直线,使得直线i的两个端点分别为(i, ai)和(i, 0)。找出两条直线,这两条直线和x轴构成一个容器,使容器中含有最多的水。
注意:你不能倾斜容器,n至少是2。
即:
找到数组中两个数,使【其中较小的数*两数之间的距离】最大
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). nvertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container and n is at least 2.
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
Input: [1,8,6,2,5,4,8,3,7] Output: 49
方法:
使【其中较小的数*两数之间的距离】最大,即其中较小的数需要更大、且两数之间的距离也要尽可能的大
使用maxA来记录当前最大距离,由于容器是两边分别有一个拦截,因此用两个loc来分别记录两边的位置,每次计算在距离loc1-loc2中的最大面积,具体方法为:
leftloc记录从0开始的位置,rightloc记录从nums.length-1开始的位置
计算当前【其中较小的数*两数之间的距离】,并与maxA进行比较,若大于,则替换;
比较leftloc和rightloc的数字大小,将较小数的位置往中间挪动一位
循环直到两位置重合
(使用这种方法,可以确保对于每个距离,所计算的面积都是最大的,不需要针对每个距离去遍历整个数组)
代码:
class Solution {
public int maxArea(int[] height) {
if(height.length<=1) {
return 0;
}
int leftLoc = 0;
int rightLoc = height.length-1;
int maxA = 0;
while(leftLoc<rightLoc) {
int small = smaller(height[leftLoc], height[rightLoc]);
// 计算面积
int tempA = (rightLoc-leftLoc)*small;
// 更新面积
if(tempA>maxA) {
maxA = tempA;
}
// 移动
if(small == height[leftLoc]) {
leftLoc++;
}else {
rightLoc--;
}
}
return maxA;
}
// 得到两个数中的较小数
public int smaller(int a,int b) {
if(a>b) {
return b;
}
return a;
}
}