題目: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.
思路:本以爲和之前的題目:Largest Rectangle in Histogram解題思路一樣,細想也不是。參考了leetcode的解法:https://leetcode.com/discuss/59635/easy-concise-java-o-n-solution-with-proof-and-explanation也許這個解法不好理解,還可以看看這個:https://leetcode.com/discuss/11482/yet-another-way-to-see-what-happens-in-the-o-n-algorithm
總結一下思路:
兩個指針:left=0 right=height.length-1 。假如left=0,right=6:
如果height[left]<height[right],則0-5 0-4 … 0-1 都要比0-6小(準確來說是不可能比0-6大),所以left++。
如果height[left]>height[right],則1-6 2-6 … 5-6 都要比0-6小(準確來說是不可能比0-6大),所以right--
代碼:
public int maxArea(int[] height) {
int left=0,right=height.length-1;
int max=0;
while(left<right){
max = Math.max(max, Math.min(height[left], height[right])*(right-left));
if(height[left]<height[right])
left++;
else
right--;
}
return max;
}