力扣刷题9

第一题:盛最多水的容器

来源:https://leetcode.cn/problems/container-with-most-water/description/

给定一个长度为n的整数数组height。有n条垂线,第i条线的两个端点是(i,0)和(i,height[i])。找出其中的两条线,使得它们与x轴共同构成的容器可以容纳最多的水。返回容器可以储存的最大水量。说明:你不能倾斜容器。

这个题我刚开始想用暴力法,但是题目给到的n的范围是,只通过了部分样例。而且很多组合的面积明显很小,完全没有必要计算,浪费了时间,所以我换成了双指针法。

这个题的难点是要确定核心的计算公式:容器的盛水量 = 两条线中较矮的高度 × 两条线之间的水平距离

主要策略是:(1)初始时,左指针在数组最左端(left=0),右指针在最右端(right=len(height-1));(2)计算当前指针位置的盛水量,并更新最大水量;(3)移动较矮的那个指针,因为移动较高的那个指针不会增加盛水量,只有移动较矮的指针才有可能找到更高的边,从而提高盛水量;(4)终止条件:但左右指针相遇时,遍历结束,返回最大水量。

以下是我的答案:

python 复制代码
from typing import List

class Solution:
    def maxArea(self, height: List[int]) -> int:
        left = 0
        right = len(height) - 1
        max_water = 0
        while left < right:
            # 计算当前面积
            current_width = right - left
            current_height = min(height[left], height[right])
            current_area = current_width * current_height
            
            # 更新最大水量
            if current_area > max_water:
                max_water = current_area
            
            # 移动较矮的指针
            if height[left] < height[right]:
                left += 1
            else:
                right -= 1
        
        return max_water

模拟一下过程:(height=[1,8,6,2,5,4,8,3,7])

初始left=0,right=8,height[left]=1,height[right]=7,面积8*1=8;

此时height[left] < height[right],移动左指针

第一次移动:left=1,right=8,height[left]=8,height[right]=7,面积7*7=49;

此时height[left] > height[right],移动右指针

第二次移动:left=1,right=7,height[left]=8,height[right]=3,面积6*3=18;

此时height[left] > height[right],移动右指针

第三次移动:left=1,right=6,height[left]=8,height[right]=8,面积5*8=40;

此时height[left] = height[right],随便移动一个,我移动的是右指针

第四次移动:left=1,right=5,height[left]=8,height[right]=4,面积4*4=16;

此时height[left] > height[right],移动右指针

第五次移动:left=1,right=4,height[left]=8,height[right]=5,面积3*5=15;

此时height[left] > height[right],移动右指针

第六次移动:left=1,right=3,height[left]=8,height[right]=2,面积2*2=4;

此时height[left] > height[right],移动右指针

第七次移动:left=1,right=2,height[left]=8,height[right]=6,面积1*6=6;

此时height[left] > height[right],移动右指针

此时left=1,right=1,不满足循环条件,跳出循环。

比较下来,最大面积为49,符合所给样例。


好了,这个题非常清晰易懂,记录完毕。

相关推荐
lihihi11 分钟前
P1209 [USACO1.3] 修理牛棚 Barn Repair
算法
weixin_3875342230 分钟前
Ownership - Rust Hardcore Head to Toe
开发语言·后端·算法·rust
xsyaaaan30 分钟前
leetcode-hot100-链表
leetcode·链表
庞轩px36 分钟前
MinorGC的完整流程与复制算法深度解析
java·jvm·算法·性能优化
Queenie_Charlie42 分钟前
Manacher算法
c++·算法·manacher
闻缺陷则喜何志丹43 分钟前
【树的直径 离散化】 P7807 魔力滋生|普及+
c++·算法·洛谷·离散化·树的直径
AI_Ming1 小时前
Seq2Seq-大模型知识点(程序员转行AI大模型学习)
算法·ai编程
若水不如远方1 小时前
分布式一致性(六):拥抱可用性 —— 最终一致性与 Gossip 协议
分布式·后端·算法
计算机安禾1 小时前
【C语言程序设计】第35篇:文件的打开、关闭与读写操作
c语言·开发语言·c++·vscode·算法·visual studio code·visual studio
Wect1 小时前
React Hooks 核心原理
前端·算法·typescript