[leetcode] 11-盛最多水的容器

1.問題

給定 n 個非負整數 a1,a2,...,an,每一個數表明座標中的一個點 (i, ai) 。在座標內畫 n 條垂直線,垂直線 i 的兩個端點分別爲 (i, ai) 和 (i, 0)。找出其中的兩條線,使得它們與 x 軸共同構成的容器能夠容納最多的水。數組

說明:你不能傾斜容器,且 n 的值至少爲 2。3d

Input: [1,8,6,2,5,4,8,3,7]
Output: 49指針

2.思路

1.暴力法
暴力解決,不解釋code

時間複雜度爲O(n^2),空間複雜度爲O(1)blog

2.雙指針法
在數組的0位置和length-1位置定義一個指針標記,計算這兩個節點的「容量」,而且設置爲最初的最大值max。編譯器

要想擴大容量,就要減小長度,增長高度,那麼要left標記向前推仍是right標記向後退呢?固然是哪一個更小搞哪一個。由於若是搞大的,那麼容量不可能變大。io

當left==right時退出循環,返回max。編譯

時間複雜度O(n),空間複雜度O(1)class

3.題解

class Solution {
   public int maxArea(int[] height) {
            int left=0;
            int right=height.length-1;
            int max=(right-left)*Math.min(height[left],height[right]);
            int newmax=0;
            int i=0;//沒什麼實際意義,只是爲了讓line 9是語句,避免編譯器報錯
            while(left!=right){
                i=height[left]<height[right]?left++:right--;
                newmax=(right-left)*Math.min(height[left],height[right]);
                max=newmax>max?newmax:max;
            }
            return max;
        }
}
相關文章
相關標籤/搜索