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.
在二维坐标系中,(i, ai) 表示 从 (i, 0) 到 (i, ai) 的一条线段,任意两条这样的线段和 x 轴组成一个木桶,找出能够盛水最多的木桶,返回其容积。
最简单的思路:两个for循环,得出所有的值,去最大值,但这个肯定超过时间限制。
public static int maxArea(int[] height) {
int maxArea = 0;
for(int i = 0; i<height.length;i++) {
for(int j = i; j < height.length;j++){
int area = Math.min(height[i], height[j])*(j-i);
if(area>maxArea) {
maxArea = area;
}
}
}
return maxArea;
}
既然不能简单使用for循环遍历所有的结果,那必然需要找规律舍弃一些组合,面积的计算公式为(j-i)*min(height[i],height[j])。例如height[i] < height[j],那i和j-2,j-2。。的组合都可以舍弃,因为j-i是最大值。所以可以计算下一个节点i+1。
因此,我们可以从头尾开始向中间遍历,当左端小于右端,则左端向右移,反之向左移;
public static int maxArea(int[] height) {
int left = 0;
int right = height.length-1;
int maxArea = 0;
while(right > left) {
int area = (right-left)*Math.min(height[right], height[left]);
if(area>maxArea){
maxArea = area;
}
if(height[right] > height[left]) {
left++;
}else {
right--;
}
}
return maxArea;
}
leetcode里面有好多题目用简单直接的思路都会超时,因此可以考虑根据规律丢弃一些计算。