当前位置:网站首页>leetcode 11. 盛最多水的容器
leetcode 11. 盛最多水的容器
2022-08-03 12:29:00 【_刘小雨】
作者简介:C/C++ 、Golang 领域耕耘者,创作者
个人主页:作者主页
活动地址: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
🧡 算法分析
此题方法之一是用贪心

方法比较巧妙, 直接说算法步骤
- 直接利用双指针,一个指向开头
left,一个指向结尾right; - 保存构成容器的面积;
- 移动指针了,这里只有两种情况
- 当前面指针指向的高度 < 后面指针指向的高度, left ++;
- 当前面指针指向的高度 >= 后面指针指向的高度, right ++;
- 更新构成容器的面积, 循环直到 left == right
- 返回构成最大面积
代码实现
class Solution {
public:
int maxArea(vector<int>& height) {
// 用双指针扫描
// 如果前面的指针高度低,前面的指针向后移动, 如果后面的指针低,后面指针向前移动
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;
}
};
执行结果:
时间复杂度分析
其中遍历一次, 时间复杂度为O(n)
如果觉得对你有帮助的话:
点赞,你的认可是我创作的动力!
🧡 收藏,你的青睐是我努力的方向!
️ 评论,你的意见是我进步的财富!
边栏推荐
- An动画优化之补间形状与传统补间的优化
- 业界新标杆!阿里开源自研高并发编程核心笔记(2022最新版)
- 实数取整写入文件(C语言文件篇)
- 622. 设计循环队列
- 博客记录生活
- 【Verilog】HDLBits题解——Verification: Writing Testbenches
- 长城简漫·暑期安全篇⑤ 这个强,不能逞
- In order to counteract the drop in sales and explore the low-end market, Weilai's new brand products are priced as low as 100,000?
- ROS中编译通过但是遇到可执行文件找不到的问题
- R language ggplot2 visualization: use the patchwork bag plot_layout function will be more visual image together, ncol parameter specifies the number of rows, specify byrow parameters configuration dia
猜你喜欢
随机推荐
使用 %Status 值
GameFi 行业下滑但未出局| June Report
【蓝桥杯选拔赛真题48】Scratch跳舞机游戏 少儿编程scratch蓝桥杯选拔赛真题讲解
安防监控必备的基础知识「建议收藏」
期货公司开户关注的关键点
[数据仓库]分层概念,ODS,DM,DWD,DWS,DIM的概念「建议收藏」
博客记录生活
How can I get a city's year-round weather data for free?Precipitation, temperature, humidity, solar radiation, etc.
什么是分布式锁?几种分布式锁分别是怎么实现的?
Five, the function calls
Free Internet fax platform fax _ don't show number
新评论接口——京东评论接口
15. PARTITIONS「建议收藏」
可重入锁详解(什么是可重入)
Feature dimensionality reduction study notes (pca and lda) (1)
【云原生 · Kubernetes】部署Kubernetes集群
Database basics one (MySQL) [easy to understand]
4500 words sum up, a software test engineer need to master the skill books
The Yangtze river commercial Banks to the interview
php microtime encapsulates the tool class, calculates the running time of the interface (breakpoint)









