題目描述
解題思路(雙指針法)
設置雙指針,分別位於容器兩端,並且更新面積最大值 res,直到 i == j 時返回 res
指針移動規則:
水槽的實際面積由左右兩端短板所決定,簡單來說就是誰短向內移動誰。
原因:若短板向內移,則實際面積必然大於或等於初始面積;若長板向內移,由於其移動導致寬度減1,導致實際面積小於或等於初始面積。
python代碼
class Solution:
def maxArea(self, height: List[int]) -> int:
i = 0
j = len(height)-1
res = 0
while i<j:
if height[i] <= height[j]:
res = max(res, height[i]*(j-i))
i += 1
else:
res = max(res, height[j]*(j-i))
j -= 1
return res
時間複雜度:O(n)。雙指針遍歷一次底邊寬度n
空間複雜度:O(1)。指針使用常數額外空間