当前位置:网站首页>leetcode 11. The container that holds the most water
leetcode 11. The container that holds the most water
2022-08-03 13:03:00 【_ xiao-yu liu】
作者简介:C/C++ 、Golang field cultivator,创作者
个人主页:作者主页
活动地址:CSDN21天学习挑战赛
题目来源: leetcode官网
如果感觉博主的文章还不错的话,还请关注 、点赞 、收藏🧡三连支持一下博主哦~~~
题目描述
给定一个长度为 n 的整数数组 height .有 n 条垂线,第 i 条线的两个端点是 (i, 0) 和 (i, height[i]) .
找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水.
返回容器可以储存的最大水量.
说明:你不能倾斜容器.

示例1:
输入:[1,8,6,2,5,4,8,3,7]
输出:49
解释:图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7].在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49.
示例2:
输入:nums = [0,0,0], target = 1
输出:0
🧡 算法分析
One way to do this is to use greed

方法比较巧妙, Let's talk about the algorithm steps directly
- 直接利用双指针,一个指向开头
left,一个指向结尾right; - Save the area that makes up the container;
- 移动指针了,这里只有两种情况
- The height that the current pointer points to < The height pointed to by the back pointer, left ++;
- The height that the current pointer points to >= The height pointed to by the back pointer, right ++;
- Updates the area that makes up the container, 循环直到 left == right
- Returns the largest area that constitutes it
代码实现
class Solution {
public:
int maxArea(vector<int>& height) {
// Scan with two pointers
// If the front pointer height is low,The front pointer moves backwards, If the pointer behind is low,后面指针向前移动
int re = 0;
for(int i = 0, j = height.size() - 1; i < j ; )
{
re = max(re, min(height[i], height[j]) * (j - i));
if(height[i] < height[j]) i++;
else j--;
}
return re;
}
};
执行结果:
时间复杂度分析
which traverse once, 时间复杂度为O(n)
如果觉得对你有帮助的话:
点赞,你的认可是我创作的动力!
🧡 收藏,你的青睐是我努力的方向!
️ 评论,你的意见是我进步的财富!
边栏推荐
猜你喜欢

How can I get a city's year-round weather data for free?Precipitation, temperature, humidity, solar radiation, etc.

GameFi 行业下滑但未出局| June Report

Image fusion SDDGAN article learning

基于php网上零食商店管理系统获取(php毕业设计)

利用ChangeStream实现Amazon DocumentDB表级别容灾复制

An工具介绍之摄像头

随机森林项目实战---气温预测

setTimeout 、setInterval、requestAnimationFrame

The common problems in the futures account summary

nacos应用
随机推荐
使用 %Status 值
[Verilog] HDLBits Problem Solution - Circuits/Sequential Logic/Latches and Flip-Flops
数据库系统原理与应用教程(075)—— MySQL 练习题:操作题 151-159(十九):综合练习
别再用if-else了,分享一下我使用“策略模式”的项目经验...
数据库系统原理与应用教程(074)—— MySQL 练习题:操作题 141-150(十八):综合练习
第3章 搭建短视频App基础架构
php microtime 封装工具类,计算接口运行时间(打断点)
从器件物理级提升到电路级
YOLOv5 training data prompts No labels found, with_suffix is used, WARNING: Ignoring corrupted image and/or label appears during yolov5 training
An动画基础之元件的影片剪辑效果
Kubernetes 网络入门
类和对象(中上)
AMS simulation
shell编程条件语句
An动画基础之元件的影片剪辑动画与传统补间
数据库系统原理与应用教程(073)—— MySQL 练习题:操作题 131-140(十七):综合练习
R语言拟合ARIMA模型并使用拟合模型进行预测推理、使用autoplot函数可视化ARIMA模型预测结果、可视化包含置信区间的预测结果
漫谈缺陷管理的自动化实践方案
R语言绘制时间序列的自相关函数图:使用acf函数可视化时间序列数据的自相关系数图
SQL分页查询_Sql根据某个字段分页