LeetCode 011: Container With Most Water
2016-05-11 10:04
369 查看
011. Container With Most Water
Difficulty: MediumGiven 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.
思路
这道题首先要弄清题意,每个非负数ai都有一条垂直于x轴的线段AB(A(i, ai),B(i, 0)),任选两条线段,使之与x轴组成的容器容量最大。虽说是要用容器装水,即立体问题,但实际上是个平面问题。木桶定律,选两线段中短的为高,宽为两线段距离,使面积最大。
选取两端的线段为起始线段,哪边较短哪边就往中间靠拢。
不管哪边向中间靠拢,宽都会减小,如果固定短的一边,长的一边向中间靠拢时,高是不可能增大的,面积只会更小;如果固定长的一边,还有增大面积的可能性。因此短的一边向中间靠拢可以不错过最大面积。
代码
[C++]class Solution { public: int maxArea(vector<int>& height) { int i = 0; int j = height.size() - 1; int maxarea = 0; while (i < j) { int minheight; if (height[i] < height[j]) { minheight = height[i]; i++; } else { minheight = height[j]; j--; } int area = minheight * (j - i + 1); maxarea = maxarea > area ? maxarea : area; } return maxarea; } };
相关文章推荐
- ovs-vsctl: unix:/usr/local/var/run/openvswitch/db.sock: database connection failed
- (总结)密码破解之王:Ophcrack彩虹表(Rainbow Tables)原理详解(附:120G彩虹表下载)
- pthread_barrier_init,pthread_barrier_wait简介
- LightOJ 1282 - Leading and Trailing(快速幂取模)
- LightOJ 1236 - Pairs Forming LCM(唯一分解定理)
- Maven Failed
- INSTALL_FAILED_INSUFFICIENT_STORAGE apk安装失败
- Failed to install XXXX.apk on device '5358baa3': timeout
- AS中无法使用AIDL描述文件问题
- HDU2389 Rain on your Parade(HK模版)
- leetcode.220. Contains Duplicate III
- poj-1273 Drainage Ditches(最大流基础题)
- Ext.Panel 面板控件、 Ext.window.Window 窗口控件、 Ext.container.Viewport 布局控件
- APS.NET_MVC5学习笔记- 查询Details和Delete方法
- leetcode 182. Duplicate Emails
- 图像特效---Oilpaint油画滤镜
- 再以Circle类为直接基类,派生出一个Cylinder(圆柱体)类,再增加数据成员h(高),,以及求圆柱表面积的成员函数area和求圆柱体积的成员函数volume,实现需要的成员函数,并设计main
- TensorFlow人工智能入门教程之十三 RCNN 区域卷积网络(视频侦测分析人脸侦测区域检测 )
- http://www.cnblogs.com/kristain/articles/2033566.html
- int main(int argc,char* argv[]),int main(int argc,char** argv)