欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > LeetCode 11 Container with Most Water 解题思路和python代码

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

2024/10/26 5:30:56 来源:https://blog.csdn.net/weixin_57266891/article/details/142737653  浏览:    关键词: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

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

class Solution:def maxArea(self, height: List[int]) -> int:left = 0right = len(height) - 1max_area = 0while left < right:# Calculate the current area width = right - leftcurrent_area = min(height[left], height[right]) * width# Update max_area if the current one is largermax_area = max(max_area, current_area)# Move the pointer that points to the shorter lineif height[left] < height[right]:left += 1else:right -= 1return max_area

Time Complexity 是 O(n)
Space Complexity 是 O(1)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com