LeetCode 11.Container With Most Water
题目:
Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container.
分析与解答:
n个数,a1到an,每个数代表一个坐标(i,ai),将每个数与各自的(0,ai)坐标相连形成一条垂直于X轴的直线。在这些直线里挑两条,形成一个容器,让这个容器在不倾斜的情况下能装最多的水。
容器的装水量取决于两个因素,一个是两个边最小的那一个的高度,另一个是两个边之间的距离。由于数组是无序的,所以高度是没有规律的因素,必须一个一个遍历,但边的距离是有规律的,所以可以设立头尾两个指针head和end,记下他们的装水量V和边的高度h1,h2,假设h1<=h2。之后往中间进行移动,如果移动较高的那条边,是不可能增加装水量的。所以只能移动较矮的那条边。移动过程中如果碰到比h1还矮的边,也是无法增加装水量的,直到遇到比h1高的边,此时重新计算装水量,如果比V大,则刷新h1,h2;否则继续移动,直到head和end相遇。
class Solution {
public:int maxArea(vector<int> &height) {int left = 0, maxArea = 0, right = height.size() - 1;while (left < right) {maxArea = max(maxArea,(right - left) * min(height[left], height[right]));if (height[left] < height[right])left++;elseright--;}return maxArea;}
};
LeetCode 11.Container With Most Water相关推荐
- 【贪心+双指针】LeetCode 11. Container With Most Water
LeetCode 11. Container With Most Water Solution1: 参考网址:http://www.cnblogs.com/grandyang/p/4455109.ht ...
- LeetCode 11 Container With Most Water
问题:给出一个数组nums,要求选择2个,使得容器中包含的水最多. 思路:假设选取x,y,其中x<y,则包含的水为min(x,y)*(index(y) - index(x)).此时应该选择在最小 ...
- leetcode 11. Container With Most Water
题意:题目大概意思就是让你找两个数使得两个数的最小值乘以他们的距离最大Area 题解:设置两个变量, 一个是从头开始,一个是从尾开始,计算两个数的Area,并更新最大值,如果开始的元素大于结尾的元素则 ...
- LeetCode 11. Container With Most Water--Java 解法--困雨水简单版
LeetCode 11. Container With Most Water–Java 解法 此文首发于我的个人博客:LeetCode 11. Container With Most Water–Ja ...
- 【LeetCode】11. Container With Most Water 解题小结
题目: Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, a ...
- leetcode -eleven:Container With Most Water
2019独角兽企业重金招聘Python工程师标准>>> Given n non-negative integers a1, a2, ..., an, where each repre ...
- 11. Container With Most Water
2019独角兽企业重金招聘Python工程师标准>>> 就是说,x轴上在1,2,...,n点上有许多垂直的线段,长度依次是a1, a2, ..., an.找出两条线段,使他们和x抽围 ...
- [贪心|双指针] leetcode 11 盛最多水的容器
[贪心|双指针] leetcode 11 盛最多水的容器 1.题目 题目链接 给你 n 个非负整数 a1,a2,-,an,每个数代表坐标中的一个点 (i, ai) .在坐标内画 n 条垂直线,垂直线 ...
- Container with most water(盛水最多的容器)
Container with most water(盛水最多的容器) 简单的证明 如图 题目: 给定 n 个非负整数 a1,a2,-,an,每个数代表坐标中的一个点 (i, ai) .在坐标内画 n ...
最新文章
- Servlet程序自动加载
- Java如何跨语言调用Python/R训练的模型
- 【数据结构与算法】数组与链表
- python设计自定义栈类_Python如何自定义模块?Python基础教程,第十讲,自定义模块...
- IDR、CRA、BLA、RASL、RADL、closed-gop、open-gop
- Linux系统性能查询命令
- MySQL_日期时间处理函数及应用
- SWEET HOME!田志喜研究员:给中国大豆“嵌入”高产基因
- 在页面里点击一个按钮后出来一个层,可以操作的那么一个层!
- 智伴机器人广西团队_{智伴AI机器人}陈涛广西南宁防城港城市合伙人-人工智能下一个风口精准蓝...
- NGUI_2.6.3_系列教程二
- linux之正则匹配命令学习笔记
- 二次规划(QP)与OSQP求解器
- 苹果CMSV10红色自适应网站模板
- AutoCAD工程制图 常见命令与注意事项全总结(120例)
- 计算机显卡模式,电脑bios设置显卡图解
- AsposeWord转pdf的正确姿势
- matlab 调节透明度_更改图像、填充或曲面的透明度
- 使用 Learner Lab 建立 WordPress 网站 (EC2)
- 语音识别(ASR)论文优选:SynthASR: Unlocking Synthetic Data for Speech Recognition