Container With Most Water
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.
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.
思路:题目意思是数轴上有一系列线,求最大两条线中间的面积。这个的case因为数量量非常大,用穷举和排序的方法效率太低。
最后使用双线扫描,线性时间内解决。其思想在注释上已解释。
具体代码如下:
public class Solution {
public static int maxArea(int[] height) {
int len = height.length;
int k = 0;
int i = 0;
int j = len - 1;
int max= 0;
int min = 0;
//从开头和结尾双线扫描,i,j为位置指针
while(i < j){
min = Math.min(height[i], height[j]);
//更新最大面积
if(max < min*(j - i)){
max = min*(j-i);
}
//从位置指针的小者计算
if(height[i] < height[j]){
k = i;
//如果右边的边比height[i]小,则右边的边肯定不是最大面积者
//因为其面积height[k]-height[j]肯定小于height[i]-height[j]
//故可直接跳过,只有当height[k] > height[i]时才跳出循环与max比较
while(k < j && height[k] <= height[i]){
k++;
}
i = k;
}else{
k = j;
//与上同
while(i < k && height[k] <= height[j]){
k--;
}
j = k;
}
}
return max;
}
}