【LeetCode系列】盛水最多問題 Container With Most Water

題目描述: LeetCode地址
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 and n is at least 2.

給定 n 個非負整數 a1,a2,…,an,每個數代表座標中的一個點 (i, ai) 。在座標內畫 n 條垂直線,垂直線 i 的兩個端點分別爲 (i, ai) 和 (i, 0)。找出其中的兩條線,使得它們與 x 軸共同構成的容器可以容納最多的水。
注: 不能傾斜容器,且 n 的值至少爲 2。

解題思路:
兩線段之間的區域總是取決於較短那條的長度。

我們在由線段長度構成的數組中使用兩個指針,left放在開始,right置於末尾。 用變量 maxArea來表示獲得的最大面積。
maxArea = min(height[left],height[right]) * (right - left)

在每一次循環中找出指針所指向的兩條線段形成的區域,更新maxArea,並將指向較短線段的指針向較長線段那端移動一步。

可以查看官方解答的動圖能有更直觀的感受。

思考: 一開始不太清楚爲什麼要將指向較短線段的指針向較長那端移動,原因是要想得到最大的區域面積,就要假設較大的那端是下次循環中較短的那端,可能可以得到更大的區域面積。

代碼:

class Solution {
    public int maxArea(int[] height) {
        int left = 0;
        int right = height.length - 1;
        int maxArea = 0;
        while(left < right){
            maxArea = Math.max(maxArea, Math.min(height[left], height[right]) * (right - left));
            if(height[left] < height[right]){
                left++;
            }else{
                right--;
            }
        }
        return maxArea;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章