刚开始用暴力循环
class Solution: def maxArea(self, height: List[int]) -> int: n=len(height) area=[] for x1 in range(n): for x2 in range(x1+1,n): width_rec= x2-x1 if height[x1]>height[x2]: height_rec= height[x2] else: height_rec= height[x1] # area.append(width_rec*height_rec)。 return max(area)
会超时,看了题解是要用双指针的方法,从两边开始移动,现在时间比较紧,晚点自己写一遍原理证明,加强印象。
官方题解
class Solution: def maxArea(self, height: List[int]) -> int: l, r = 0, len(height) - 1 ans = 0 while l < r: area = min(height[l], height[r]) * (r - l) ans = max(ans, area) if height[l] <= height[r]: l += 1 else: r -= 1 return ans 作者:LeetCode-Solution 链接:https://leetcode-cn.com/problems/container-with-most-water/solution/sheng-zui-duo-shui-de-rong-qi-by-leetcode-solution/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)