Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical 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.
翻译:给定n个非负整数a1,a2,...,an,其中每个表示坐标(i,ai)处的点。 绘制n条垂直线,使得线i的两个端点在(i,ai)和(i,0)。 找到两条线,其与x轴一起形成容器,使得容器包含最多的水。
注意:您不能倾斜容器,n至少为2。
分析:也就是计算最大容量,第一考虑是直接暴力试试看会有什么结果。
public class Solution {
public int maxArea(int[] height) {
int len = height.length;
int high , max=0;
for(int i = 1 ; i < len ; i++){
for(int j = 0 ; j < i ; j++){
high = (i - j)*min(height[i],height[j]);
if(high>max){
max = high;
}
}
}
return max;
}
public int min(int a , int b){
if(a>b)
return b;
else return a;
}
}
思路是每一次计算所有下标不大于i的容量,如果有大于以前算出来的容量就替换。
然后结果是很自然的TLE。
可能扫描的方法可以优化。因为要扫描某两个数作为容器的两边,在数组左右分别设定两个指针,然后两者比较时较小的向中间移动,这样总是能够将最大的容积扫描到。以下简单证明一下,如果第3个和第10个相间的为最大容积,那么在左边到达第3个时,右边是能够因为第11个小于3而往中间移动,也就是右边移动到10,否则就会3与11之间的容积一定大于3与10,与假设矛盾了。再考虑左边与右边类似, 所以这样的O(n)算法也是可以满足的。
public class Solution {
public int maxArea(int[] height) {
int left = 0 , right = height.length-1;
int con , max = 0;
while(left < right){
con = (right - left)*min(height[left],height[right]);
if(con > max) max = con;
if(height[left] > height[right]) right--;
else left++;
}
return max;
}
public int min(int a , int b){
if(a>b)
return b;
else return a;
}
}