ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

元宝 LeetCode 11. 盛最多水的容器 Python3实现

元宝    LeetCode 11. 盛最多水的容器 Python3实现 LeetCode 11. 盛最多水的容器思路双指针法核心思想容器的盛水量由两端中较短的板和两板之间的距离决定。算法初始化左右指针left 0,right n-1计算当前面积min(height[left], height[right]) * (right - left)移动较矮的那一端的指针因为短板限制了容量移动长板不可能增大面积重复直到两指针相遇时间复杂度O(n)空间复杂度O(1)Python3 实现class Solution: def maxArea(self, height: List[int]) - int: left, right 0, len(height) - 1 max_area 0 while left right: # 计算当前面积 current_area min(height[left], height[right]) * (right - left) max_area max(max_area, current_area) # 移动较矮的指针 if height[left] height[right]: left 1 else: right - 1 return max_area为什么移动较矮的指针假设height[left] height[right]当前容量 height[left] × (right - left)如果移动右指针长板宽度减小且高度上限仍是height[left]容量一定不会增大如果移动左指针短板虽然宽度也减小但高度上限可能变大容量有可能增大因此只有移动短板才有机会找到更大的面积。示例输入height [1,8,6,2,5,4,8,3,7] 输出49 解释选取 index1 (高度8) 和 index8 (高度7)面积 min(8,7) × 7 49输入height [1,1] 输出1
返回列表