吴师兄学算法day07 11. 盛最多水的容器

题目:11. 盛最多水的容器

难点:

  • 如何确定,每次只移动最短边,
  • 因为无论移动哪边的柱子,下面的底部一定是缩短的,剩下的就是取决于高度。
    • 如果移动的是,两侧高的那个,整体的面积一定是缩小的。
    • 如果移动的是,两侧底的那个,后面的柱子有可能是遇到高的,也有可能是低的,所以,整体面积可能大,也可能小
  • 参考了K神的解题思路。

我的代码:

参考思路后,自己写的代码:

class Solution:
    def maxArea(self, height: List[int]) -> int:
        left = 0
        right = len(height) -1
        # 面积S=高*底  本题高度由短边决定
        # s = min(height[left],height[right])*(right-left)
        ans = 0
        while left < right: # 每次移动短边            
            s = min(height[left],height[right]) * (right-left)
            ans = max(ans,s)    # 记录每次的最大值
            # 移动短边
            if height[left]<height[right]:
                left+=1
            else:
                right -=1
        return ans

K神的代码:

class Solution:
    def maxArea(self, height: List[int]) -> int:
        i, j, res = 0, len(height) - 1, 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

作者:Krahets
链接:https://leetcode.cn/problems/container-with-most-water/solutions/11491/container-with-most-water-shuang-zhi-zhen-fa-yi-do/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

老师的代码:

# https://www.algomooc.com/587.html
# 作者:程序员吴师兄
# 代码有看不懂的地方一定要私聊咨询吴师兄呀
# 盛最多水的容器 ( LeetCode 11) : https://leetcode-cn.com/problems/container-with-most-water/
class Solution:
    def maxArea(self, height: List[int]) -> int:
       # 设置两个索引,分别指向容器的两侧

       # 索引 left 指向最左边的柱子
       left = 0

       # 索引 right 指向最右边的柱子
       right = len(height) - 1

       # 设置一个变量用来保存当下水的最大面积
       res = 0

       # 移动 left 和 right,直到 left 和 right 相遇为止
       while left < right :

           # 水的宽度是 right - left
           width = right - left

           # 水的高度由两根柱子最短的那根决定
           h = min(height[left],height[right])

           # 计算此时水的面积
           area = width * h

           # 如果此时水的面积大于了我们之前保存的那个值,我们需要更新一下
           if area >= res :
               # 更新 res 的值为 area,确保 res 一直都是最大的值
               res = area
           
           # 接下来去观察需要移动哪根柱子:必定是最短的那根柱子

           # 如果左边的柱子更短,那么向内移动左边的柱子,因为只有这样,才有可能找到一个更高的水面
           # 在宽度一定变小的情况下,水的面积才有可能增大
           if height[left] < height[right] :
               # 向内移动左边的柱子
               left += 1

           # 如果右边的柱子更短,那么向内移动右边的柱子,因为只有这样,才有可能找到一个更高的水面
           # 在宽度一定变小的情况下,水的面积才有可能增大
           else:
               # 向内移动右边的柱子
               right -= 1
            
       # 最后返回最大的面积 res 即可
       return res

 

总结:

  • 不会就多看,多学。学习使我快乐!!

参考:

https://r07na4yqwor.feishu.cn/docx/WcAVdEBD5o8DhQxIqkccvDZqnHh

Krahets题解链接

posted @ 2024-01-15 11:26  o蹲蹲o  阅读(2)  评论(0编辑  收藏  举报