日期:2026年10月18日
LeetCode 題目連結:11. Container With Most Water
解題想法
中等難度題。題目給一個長度為 $n ~(2 \leq n \leq 10^5)$ 的整數陣列 $height ~(0 \leq height[i] \leq 10^4)$,代表位置 $i$ 有一面 $(i, 0)$ 到 $(i, height[i])$ 的牆壁,如果取其中兩面牆壁作為容器,求最大的容積為何?
由於 $n$ 不大,用兩個 for 迴圈跑所有的牆壁組合也能通過,但是這樣寫很慢。提示有說要用雙指針 (two pointer),假設 $left$、$right$ 分別指向左側、右側牆壁的位置,由兩側向中間移動找最大容積,接下來選擇當時較低的牆壁往中間移動,直到 $left$、$right$ 重合為止。
Python 程式碼
Runtime: 56 ms, beats 62.51%. Memory: 29.36 MB, beats 97.91%.
class Solution:
def maxArea(self, height: list[int]) -> int:
left = 0 # 左側牆壁索引值
right = len(height) - 1 # 右側牆壁索引值
ans = 0 # 答案
# 由兩側往中間移動牆壁找答案
while left < right:
lh = height[left] # 左側牆壁高度
rh = height[right] # 右側牆壁高度
vol = min(lh, rh) * (right - left) # 目前的體積,高度取 lh, rh 較小值
ans = max(ans, vol) # 更新答案
# lh, rh 較小的一側向中間移動
if lh < rh: left += 1
else: right -= 1
return ans
C++ 程式碼
Runtime: 2 ms, beats 38.44%. Memory: 62.83 MB, beats 77.89%.
class Solution {
public:
int maxArea(vector<int>& height) {
int left = 0; // 左側牆壁索引值
int right = height.size() - 1; // 右側牆壁索引值
int ans = 0; // 答案
/* 由兩側往中間移動牆壁找答案 */
while(left < right) {
int lh = height[left]; // 左側牆壁高度
int rh = height[right]; // 右側牆壁高度
int vol = min(lh, rh) * (right - left); // 目前的體積,高度取 lh, rh 較小值
ans = max(ans, vol); // 更新答案
// lh, rh 較小的一側向中間移動
if (lh < rh) left++;
else right--;
}
return ans;
}
};
C 語言程式碼
Runtime: 2 ms, beats 30.70%. Memory: 14.82 MB, beats 9.44%.
#define min(a, b) ((a) < (b) ? (a) : (b))
#define max(a, b) ((a) > (b) ? (a) : (b))
int maxArea(int* height, int heightSize) {
int left = 0; // 左側牆壁索引值
int right = heightSize - 1; // 右側牆壁索引值
int ans = 0; // 答案
/* 由兩側往中間移動牆壁找答案 */
while(left < right) {
int lh = height[left]; // 左側牆壁高度
int rh = height[right]; // 右側牆壁高度
int vol = min(lh, rh) * (right - left); // 目前的體積,高度取 lh, rh 較小值
ans = max(ans, vol); // 更新答案
// lh, rh 較小的一側向中間移動
if (lh < rh) left++;
else right--;
}
return ans;
}
沒有留言:
張貼留言