当前位置:网站首页>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)
如果觉得对你有帮助的话:
点赞,你的认可是我创作的动力!
🧡 收藏,你的青睐是我努力的方向!
️ 评论,你的意见是我进步的财富!
边栏推荐
- 为冲销量下探中低端市场,蔚来新品牌产品定价低至10万?
- 一些测试相关知识
- [Verilog] HDLBits Problem Solution - Verification: Writing Testbenches
- An动画基础之按钮动画与基础代码相结合
- 基于php家具销售管理系统获取(php毕业设计)
- From the physical level of the device to the circuit level
- [Verilog] HDLBits Problem Solution - Circuits/Sequential Logic/Latches and Flip-Flops
- (through page) ali time to upload the jar
- Feature dimensionality reduction study notes (pca and lda) (1)
- 解决oracle安装在linux中jdk的冲突
猜你喜欢
An introduction to the skeleton tool
什么是分布式锁?几种分布式锁分别是怎么实现的?
ECCV 2022 | AirDet: 无需微调的小样本目标检测方法
基于php网上零食商店管理系统获取(php毕业设计)
【精品必知】Pod生命周期
基于php校园医院门诊管理系统获取(php毕业设计)
Feature dimensionality reduction study notes (pca and lda) (1)
如何免费获得一个市全年的气象数据?降雨量气温湿度太阳辐射等等数据
How can I get a city's year-round weather data for free?Precipitation, temperature, humidity, solar radiation, etc.
An动画优化之遮罩层动画
随机推荐
nacos应用
An工具介绍之形状工具及渐变变形工具
(through page) ali time to upload the jar
基于php家具销售管理系统获取(php毕业设计)
浅谈低代码平台远程组件加载方案
An动画优化之遮罩层动画
Kubernetes 网络入门
An动画基础之元件的影片剪辑效果
Database basics one (MySQL) [easy to understand]
类型转换、常用运算符
Sogou news-数据集
pandas连接oracle数据库并拉取表中数据到dataframe中、筛选当前时间(sysdate)到一天之前的所有数据(筛选一天范围数据)
基于php志愿者服务平台管理系统获取(php毕业设计)
第十五章 源代码文件 REST API 简介
setTimeout, setInterval requestAnimationFrame
Blog records life
项目概述、推送和存储平台准备
Mysql重启后innodb和myisam插入的主键id变化总结
shell编程条件语句
数据库系统原理与应用教程(073)—— MySQL 练习题:操作题 131-140(十七):综合练习