[leetcode] 11. Container With Most Water
来源:互联网 发布:php表格代码 编辑:程序博客网 时间:2024/04/30 15:49
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.
这道题是找最大容器,题目难度为Medium。
双层循环暴力比对的方法估计会超时,就不尝试了。
我们拿a1和an组成的容器作为初始容器,容器容积为min(a1,an)*(n-1),把(n-1)记为长,min(a1,an)记为高。计算容器容积时要考虑到长的因素,以min(a1,an)为高的其他任何容器都不会比初始值大,因为其他容器高最大为min(a1,an),而长必定小于(n-1),所以a1和an中小的那条线在后续比较中就可以不考虑了。如果min(a1,an)==a1,我们继续查看a2和an组成的容器,否则查看a1和an-1组成的容器,同时更新最大容器值。依照这样的策略逐步缩小范围,最终就得到了最大容器。具体代码:
class Solution {public: int maxArea(vector<int>& height) { int l = 0, r = height.size()-1; int maxWater = 0; while(l < r) { maxWater = max(maxWater, min(height[r],height[l])*(r-l)); if(height[l] < height[r]) ++l; else --r; } return maxWater; }};
0 0
- LeetCode 11. Container With Most Water
- [LeetCode]11.Container With Most Water
- LeetCode --- 11. Container With Most Water
- LeetCode 11.Container With Most Water
- [Leetcode] 11. Container With Most Water
- [leetcode] 11.Container With Most Water
- 【leetcode】11. Container With Most Water
- [LeetCode]11. Container With Most Water
- 11. Container With Most Water LeetCode
- leetcode 11. Container With Most Water
- leetcode 11.Container With Most Water
- [LeetCode OJ]11. Container With Most Water
- [leetcode] 11. Container With Most Water
- Leetcode 11. Container With Most Water
- leetcode 11.Container With Most Water
- leetcode 11. Container With Most Water
- LeetCode 11. Container With Most Water
- LeetCode *** 11. Container With Most Water
- iOS Core Animation Advanced Techniques的学习笔记(五)
- NFS mount
- Android C++层的内存收回机制
- iOS-MultipeerConnectivity框架开发(一)
- 【c/c++】单链表、头指针、头结点、首元节点
- [leetcode] 11. Container With Most Water
- USACO 2016 Jan Bronze 2.Angry Cows 愤怒的奶牛
- poj 2478 Farey Sequence(欧拉函数)
- 关于QT的QProcess运行外部程序的问题
- git库服务器更改IP后设置
- 用MATLAB畫925hPa位勢高度分布圖
- eclipse导入github上面的工程
- wamp环境项目连接虚拟机mongo出现连接失败,原因是防火墙端口没开
- Qt QEventLoop 的使用两例