我現(xiàn)在在做一個叫《leetbook》的開源書項目,把解題思路都同步更新到github上了,需要的同學可以去看看
地址:https://github.com/hk029/leetcode
這個是書的地址:https://hk029.gitbooks.io/leetbook/
這里寫圖片描述
- Container With Most Water[M]
問題
<font size=4>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.
<font size=4>Note: You may not slant the container.
思路
<font size=4>首先要明確一個我之前一直理解錯的,它的題目是<font color=red>隨意找2個木板構(gòu)成木桶,容量最大,</font>我之前以為是所有的木板已經(jīng)在它的位置上了,然后找其中容量最大的——你加的水是可以漫過中間比較短的板子的。
<font size=4>如果按題意來,就簡單了。
<font size=4>我們用兩個指針來限定一個水桶,left,right。
<font size=4>h[i]表示i木板高度。
<font size=4>Vol_max表示木桶容量最大值
<font size=4>由于桶的容量由最短的那個木板決定:
Vol = min(h[left],h[right]) * (right - left)
- <font size=4>left和right分別指向兩端的木板。
- <font size=4>left和right都向中央移動,每次移動left和Right中間高度較小的(因為反正都是移動一次,寬度肯定縮小1,這時候只能指望高度增加來增加容量,肯定是替換掉高度較小的,才有可能找到更大的容量。)
- <font size=4>看新桶子的容量是不是大于Vol_max,直到left和right相交。
<font size=4>代碼如下:
public class Solution {
public int maxArea(int[] height) {
int l = 0,r = height.length-1;
int i = height[l] > height[r] ? r:l;
int vol,vol_max = height[i]*(r-l);
while(l < r)
{
if(height[l] < height[r]) l++;
else r--;
vol = Math.min(height[l],height[r]) * (r - l);
if(vol > vol_max) vol_max = vol;
}
return vol_max;
}
}