LEETCODE: Container With Most Water
来源:互联网 发布:mac vi 命令大全 编辑:程序博客网 时间:2024/04/30 09:58
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平方的算法,不过没有通过LEETCODE的测试。所以,必须找到一个时间效率更高的算法。
假设我们用两个指针,一个指向左边left,一个指向右边right。这个时候我们会有一个初始的容量。如果left的高度小于right的高度,那么我们知道right往左移动是不会得到我们想要的,只有left往右移动。(如果我们把right往左移动,容量是right新的位置和left中的小值乘上距离。)反之,right往左移动。
class Solution {public: int maxArea(vector<int> &height) { int left = 0; int right = height.size() - 1; int max = 0; while(left < right) { int length = right - left; int temp = length * (height[left] < height[right] ? height[left] : height[right]); max = max > temp ? max : temp; if(height[left] < height[right]) left ++; else right --; } return max; }};
0 0
- 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
- Any、AnyObject、AnyClass区别
- mtd层次分析
- 微信切忌跑马圈地:即时通讯2B市场硝烟四起
- C++重载,重写
- myeclipse快捷键
- LEETCODE: Container With Most Water
- shell循环读取文件
- Vim配置
- 开发者账号注册申请
- VS2010安装MSDN(转载)
- Arm-linux-gcc安装步骤
- 字符串相似度算法
- 数组与汇编的理解
- XFire实现身份验证(基于Xfire SOAP Header的WebService安全验证)