11. Container With Most Water
来源:互联网 发布:远盾网络 编辑:程序博客网 时间:2024/05/16 09:43
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条竖直的线段,从中选出两条使其与x轴组成容器,使容器的面积最大。
思路:1. 假定选定的两条线为C(i, j),则j之后一定没有线比aj更高,同样i之前一定没有线比ai更高。 2. 假定目前已有一个较佳的区间[x, y],那么问题的求解就限定在区间[x, y]内的那些(ai>=ax, aj>=ay)的线上。可以逐步缩减空间。 3. 在空间逐步缩减时要注意:每次从ai,aj两条线中的较小的线开始移动到下一待选位置。因为高的那条线迟早还要和其他线组成待测容器, 较矮的那条线则不用继续测了。算法的时间复杂度为O(n)。
class Solution {public:int maxArea(vector<int>& height) {int size = height.size();if (size < 2)return 0;int area = 0;int i = 0, j = size - 1;while (i < j){int tmp;if (height[i] < height[j]){int a = height[i];tmp = a *(j - i);i++;while (i < j && height[i] <= a)i++;}else{int a = height[j];tmp = a *(j - i);j--;while (j>i && height[j] <= a)j--;} if (tmp > area)area = tmp;}return area;}};
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
- hdu 4146 Flip Game【思维+暴力】
- [090626]痕 ~きずあと~【日文硬盘版】[痕+雫&Origin][全CG存档&攻略=日本语启动+打开存档补丁]
- NWERC 2012 Foul Play 构造 (uvaLive 6271 )
- 有哪些让你相见恨晚的 PPT 制作技术或知识?
- 全系统动态污点分析-概要
- 11. Container With Most Water
- 由二进制翻转问题引发的思考
- leetcode之Ugly Number
- java和asp程序,格式化日期的函数
- 国际信息学奥林匹克竞赛(IOI)竞赛语言由三门变为五门
- Bzoj2648:SJY摆棋子:K-D-Tree
- HTML学习笔记(十三)字符实体
- Sencha Touch 历史支持
- Mysql主键索引创建的实例