11. Container With Most Water
来源:互联网 发布:淘宝特卖网 编辑:程序博客网 时间:2024/06/05 13:35
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.
解法思路:这道题其实求不规则矩形的最大长方形面积,依然是贪心算法,我们首先计算出首尾相连的矩形的长方形面积,因为这是长最大的矩形的面积,接下来我们想找到这最优解的话,肯定是要向中间移动,而这移动必然使得长度减少,那么只有高度增高,才能使得面积更大;因此我们找出更高的最小高,所以要分为两种情况,当左边的高低于右边的高,我们必然使得,左边的点向右移,找到第一个比他高的边,使得面积更大,左边高于右边时,同理,同理左边移动,找到更高的边;
class Solution {public: int maxArea(vector<int>& height) { int containerWater = 0; int pt,i,j; int head = 0; int end = height.size()- 1; while (end > head){ pt = min(height[head], height[end]); containerWater = max(containerWater,pt*(end- head)); if(height[head] < height[end]) { i = 1; while(height[head] > height[head + i]) i++; head += i; }else{ j = 1; while(height[end]> height[end-j]) j++; end -= j; } } return containerWater; }};
运行结果
阅读全文
0 0
- 11.Container With Most Water
- 11. Container With Most Water
- 11. Container With Most Water
- 11. Container With Most Water
- 11. Container With Most Water
- 11. Container With Most Water
- 11. Container With Most Water
- 11. Container With Most Water
- 11. Container With Most Water
- 11. Container With Most Water
- 11. Container With Most Water
- 11. Container With Most Water
- 11.Container With Most Water
- 11. Container With Most Water
- 11. Container With Most Water
- 11. Container With Most Water
- 11. Container With Most Water
- 11. Container With Most Water
- JavaScript高级程序设计笔记-第八章
- 如何开启mysql的事务支持
- MySQL 最基本的SQL语法/语句
- 【JAVA集合详解】Java ConcurrentModificationException异常原因和解决方法
- JAVA FTPClient FTP简单操作
- 11. Container With Most Water
- 有向无环图(DAG)拓扑排序的两种方法
- 彻底弄懂最短路径问题
- Linux菜鸟笔记——文件与目录的压缩与打包
- sublimeText的列编辑
- linux系统日常管理
- hex文件格式
- java wait notify notifyAll and 多线程顺序打印ABCD
- HDU 4775 Infinite Go 并查集