這題是一個運用雙指標的算法,目標是找到可裝最多水的容器 (面積),只需一個 while 迴圈就可依依遍歷到最大的面積答案,時間複雜度可估 O(n),這裡有 JAVA 和 Python 的寫法。
題目
You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store. Notice that you may not slant the container.
給定一個長度為 n 的整數陣列 height ,畫了 n 條的垂直線,第 i 條線的兩個端點是 (i, 0) 和 (i, height[i]) 找到兩條線與方向 x 軸一起形成的容器,使得這個容器包含最多的水 回傳可裝最大容量的水的容器 注意 你不行傾斜容器
n == height.length 2 <= n <= 105 0 <= height[i] <= 104
範例
1 2 3
Input: height = [1,8,6,2,5,4,8,3,7] Output: 49 Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In thiscase, the max area of water(blue section) the container can contain is 49.