leetcode Container With Most Water
来源:互联网 发布:开淘宝网店视频教程 编辑:程序博客网 时间:2024/06/08 14: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.
Note: You may not slant(倾斜) the container.
两边设一个指针,然后计算area,如果height[i] <= height[j],那么i++,因为在这里height[i]是瓶颈,j往里移只会减少面积,不会再增加area。
这是一个贪心的策略,每次取两边围栏最矮的一个推进,希望获取更多的水。
可以做简单证明。
如图,L1<R1<R2<L2,那么在L1移动到L2和R1移动到R2的过程中,存在的Lx和Rx都满足Lx < L1, Rx < R1。假设Lx < Rx,那么Lx* d(Rx - Lx) < L1*d(Rx-Lx) < L1 * ( R1 - L1)。若Lx > Rx,则Rx * d(Rx - Lx) < Rx * d(R1 - L1) < L1 * d(R1 - L1) (因为Rx,Lx都小于L1<R1)。直观的想就是,如果宽度减少,同时左右两侧的板都比原来的还要矮,怎么可能容纳更多的水呢?
class Solution {public: int maxArea(vector<int> &height) { int i = 0; int j = height.size()-1; int max = 0; int area = 0; while(i<j) { area = (j-i) * (height[j]>=height[i]? height[i] : height[j]); if(area>max) max = area; if(height[j]>=height[i]) i++; else j--; } return max; }};
- LeetCode: Container With Most Water
- [LeetCode]Container With Most Water
- LeetCode Container With Most Water
- LeetCode: Container With Most Water
- [Leetcode] Container With Most Water
- Leetcode: Container With Most Water
- [LeetCode] Container With Most Water
- LeetCode Container With Most Water
- [Leetcode] Container With Most Water
- [LeetCode]Container With Most Water
- LeetCode-Container With Most Water
- Container With Most Water leetcode
- LeetCode - Container With Most Water
- LeetCode: Container With Most Water
- Leetcode: Container With Most Water
- 【LeetCode】Container With Most Water
- Leetcode: Container With Most Water
- LeetCode:Container With Most Water
- 循环语句
- ListView自定义adapter中处理多事件
- Android ContentProvider组件
- 通用定时器产生PWM
- 原来Http的请求方式不止GET POST
- leetcode Container With Most Water
- Longest Consecutive Sequence 优化强迫症第二弹
- VDAL心得
- wap页适配解决页面的左、上间距问题
- 几篇不错的disruptor的入门文章
- 编程查找两个字符串最大公共子串
- 快速排序算法C++实现[评注版]
- 博客开博啦
- 简单优化:Zipalign