Leetcode 11 Container With Most Water
来源:互联网 发布:怎么理解js面向对象 编辑:程序博客网 时间:2024/06/06 13:09
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方暴力扫两边,但是看到题目难度是medium之后,我就知道一定有更优美的做法。
对,就是用两点法,其实本质是一种贪心,先说思路再来解释原理。
以起始点为两端向中间缩,记录面积的最大值,每次向内移动高度较小的一方。
因为向内移动每次X轴上的长度都会减少1,所以要想获得更大的面积就必须依赖于Y轴上的长度增加,
而Y长度由两端的较小者决定,所以移动高度较小的一方。
这里就有问题了,如果两者高度一样该怎么办呢?我想了有一会儿。
在高度一样的情况下,随便移动哪一端都是没有问题的!
因为向中间移的过程中,真正有可能刷新最大面积的是两个更高的Y轴长度,
所以如果中间还有面积更大的情况,不论先移动哪一边,最后都一定会移动至两个更高的位置。
class Solution {public: int maxArea(vector<int>& height) { int l=0,r=height.size()-1; int result=0; while(l<r) { result=max(result,(r-l)*min(height[l],height[r])); if(height[l]<height[r]) l++; else r--; } return result; }};
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
- leetcode 11 Container With Most Water
- leetcode-11 Container With Most Water
- Container With Most Water - LeetCode 11
- [Leetcode 11, Medium] Container With Most Water
- 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-11Container With Most Water
- leetcode 11 -- Container With Most Water
- 多线程NSOperation和NSOperationQueue
- iOS开发------Apple Pay(PassKit.framework篇)
- C#中int与string间转化
- ZZNU 1988 (大数取余)
- 正则表达式之密码效验(检验密码是含有小写字母、大写字母、数字、特殊符号的两种及以上)
- Leetcode 11 Container With Most Water
- 注册exe为windows系统服务
- 通过jQuery Ajax使用FormData对象上传文件
- 关于Binder在Java上工作的一点愚见(二)
- 删除系统app
- 关于一点小小的技术分享
- 操作通讯录(AddressBook篇)&通讯录UI(AddressBookUI篇)
- C++静态的方法调用成员
- c标签foreach循环list嵌套