LeetCode 11 Container with Most Water 解题思路和python代码

题目:

You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).

Find two lines that together with the x-axis form a container, such that the container contains the most water.

Return the maximum amount of water a container can store.

Notice that you may not slant the container.

Example 1:

Input: height = [1,8,6,2,5,4,8,3,7]

Output: 49

Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example 2:

Input: height = [1,1]

Output: 1

Constraints:

n == height.length

2 <= n <= 105

0 <= height[i] <= 104

解题思路:

我们可以看到这里水的体积多少取决于两边的竖直线中较短的那一条。我们可以使用两个指针,一个指向数组的第一个数,另一个指向数组的第二个数。我们可以计算面积,同时移动两个指针中,指向较短竖直线的那一个。

python 复制代码
class Solution:
    def maxArea(self, height: List[int]) -> int:
        left = 0
        right = len(height) - 1
        max_area = 0
        
        while left < right:
        	# Calculate the current area 
            width = right - left
            current_area = min(height[left], height[right]) * width

			# Update max_area if the current one is larger
            max_area = max(max_area, current_area)

			# Move the pointer that points to the shorter line
            if height[left] < height[right]:
                left += 1
            else:
                right -= 1
        return max_area
        

Time Complexity 是 O(n)

Space Complexity 是 O(1)

相关推荐
喂完待续3 小时前
【Tech Arch】Spark为何成为大数据引擎之王
大数据·hadoop·python·数据分析·spark·apache·mapreduce
王者鳜錸4 小时前
PYTHON让繁琐的工作自动化-猜数字游戏
python·游戏·自动化
若天明5 小时前
深度学习-计算机视觉-微调 Fine-tune
人工智能·python·深度学习·机器学习·计算机视觉·ai·cnn
无聊的小坏坏5 小时前
拓扑排序详解:从力扣 207 题看有向图环检测
算法·leetcode·图论·拓扑学
倔强青铜三6 小时前
苦练Python第39天:海象操作符 := 的入门、实战与避坑指南
人工智能·python·面试
一百天成为python专家7 小时前
Python循环语句 从入门到精通
开发语言·人工智能·python·opencv·支持向量机·计算机视觉
Sunhen_Qiletian7 小时前
朝花夕拾(五)--------Python 中函数、库及接口的详解
开发语言·python
三年呀7 小时前
标题:移动端安全加固:发散创新,筑牢安全防线引言:随着移动互联网
网络·python·安全
关山8 小时前
MCP实战
python·ai编程·mcp
浮灯Foden8 小时前
算法-每日一题(DAY13)两数之和
开发语言·数据结构·c++·算法·leetcode·面试·散列表