《LeetBook》leetcode題解(11):Container With Most Water[M] ——用兩個指標在陣列內移動
阿新 • • 發佈:2019-01-27
我現在在做一個叫《leetbook》的免費開源書專案,力求提供最易懂的中文思路,目前把解題思路都同步更新到gitbook上了,需要的同學可以去看看
書的地址:https://hk029.gitbooks.io/leetbook/
011. Container With Most Water[M]
問題
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.
思路
首先要明確一個我之前一直理解錯的,它的題目是隨意找2個木板構成木桶,容量最大,我之前以為是所有的木板已經在它的位置上了,然後找其中容量最大的——你加的水是可以漫過中間比較短的板子的。
如果按題意來,就簡單了。
我們用兩個指標來限定一個水桶,left,right。
h[i]表示i木板高度。
Vol_max表示木桶容量最大值
由於桶的容量由最短的那個木板決定:
Vol = min(h[left],h[right]) * (right - left)
- left和right分別指向兩端的木板。
- left和right都向中央移動,每次移動left和Right中間高度較小的(因為反正都是移動一次,寬度肯定縮小1,這時候只能指望高度增加來增加容量,肯定是替換掉高度較小的,才有可能找到更大的容量。)
- 看新桶子的容量是不是大於Vol_max,直到left和right相交。
程式碼如下:
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;
}
}