当前位置:首页 > 编程笔记 > 正文
已解决

leetCode 11. 盛最多水的容器 + 双指针

来自网友在路上 162862提问 提问时间:2023-10-20 06:08:20阅读次数: 62

最佳答案 问答题库628位专家为你答疑解惑

11. 盛最多水的容器 - 力扣(LeetCode)icon-default.png?t=N7T8https://leetcode.cn/problems/container-with-most-water/description/?envType=study-plan-v2&envId=top-interview-150

给定一个长度为 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:

输入:height = [1,1]
输出:1

class Solution {
public:int maxArea(vector<int>& height) {int n = height.size();int left=0,right=n-1;int ans=0;while(left<right) {int area = min(height[left],height[right])*(right-left);ans = max(ans,area);if(height[left] > height[right]) --right;else ++left;// height[left] > height[right] ? --right : ++left;}return ans;}
};

推荐文章:

11. 盛最多水的容器 - 力扣(LeetCode)icon-default.png?t=N7T8https://leetcode.cn/problems/container-with-most-water/solutions/11491/container-with-most-water-shuang-zhi-zhen-fa-yi-do/?envType=study-plan-v2&envId=top-interview-150

查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"leetCode 11. 盛最多水的容器 + 双指针":http://eshow365.cn/6-20114-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!