当前位置: 首页 > news >正文

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)

http://www.lryc.cn/news/455642.html

相关文章:

  • 【深度学习】损失函数
  • 力扣 中等 46.全排列
  • LabVIEW机床加工监控系统
  • 第五届智能设计国际会议(ICID 2024)
  • 厨房用品分割系统源码&数据集分享
  • 【HTTPS】深入解析 https
  • Axios 快速入门
  • LabVIEW提高开发效率技巧----调度器设计模式
  • python之认识变量
  • c++应用网络编程之十Linux下的Poll模式
  • [C++][第三方库][RabbitMq]详细讲解
  • Next.js 详解
  • pygame--超级马里奥(万字详细版)
  • 【运维】nginx静态代理资源403权限问题
  • java家政预约上门系统源码,家政服务平台源码,基于SpringBoot框架,数据库使用MySQL,界面渲染采用Thymeleaf技术开发
  • 算法知识点————贪心
  • python数据分析
  • UGUI(现成组合控件)
  • 软件交付体系文件(Word源资料)
  • 【视频目标分割-2024CVPR】Putting the Object Back into Video Object Segmentation
  • 掌握 C# 文件和输入输出操作
  • k8s 中的金丝雀发布(灰度发布)
  • 《IDEA:让编程效率翻倍的强大工具》
  • Docker 部署 Prometheus+Grafana 监控系统快速指南
  • No.8 笔记 | SQL 查询语句:数据探索的钥匙
  • 全局数据在Python包中模块间管理方法探讨
  • 无人机在矿业领域的应用!
  • 基于JavaWeb开发的java springmvc+mybatis学生考试系统设计和实现
  • 【CKA】四、etcd的备份与恢复
  • 基于Arduino的SG90舵机驱动