題目:
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.
給定一個height長度為 的整數數組n。其中繪製了兩條垂直線,使得線n的兩個端點分別為和。ith(i, 0)(i, height[i])
求兩條線,與 x 軸一起形成一個容器,使得容器中裝有最多的水。
返回容器可以儲存的最大水量。
請注意,不要傾斜容器。
題目說明
給一個長度為 n 的整數陣列 height,其中每個元素代表一條直線的高度,座標為 (i, height[i])。任選兩條線與 x 軸構成一個容器,容器能裝水的容量取決於:
解題思路
暴力法 (Brute Force)
枚舉所有兩條線,計算容量,取最大值。
時間複雜度 O(n²),會超時。
雙指針法 (最佳解)
用兩個指標 left、right 指向陣列兩端。
計算當前容量 min(height[left], height[right]) * (right - left)。
更新最大值。
移動較矮的那一邊:
因為容量取決於 較矮的一邊,移動較高的一邊不可能增加容量。
不斷縮小區間直到 left >= right。
時間複雜度 O(n)。