[LeetCode]--Container With Most Water
来源:互联网 发布:网络剧投资 编辑:程序博客网 时间:2024/06/16 09:12
题目
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.
时间复杂度为O(n^2)。
Note: You may not slant the container and n is at least 2.
中文题意:由非负整数 a1, a2, ..., an, 分别代表坐标 (i, ai),n条垂直于x轴的线段i及由(i, ai)和 (i, 0)作为端点组成。请找到两条线段,与x轴组成一个容器,使得这个容器盛水最多。
注意:容器不能倾斜且只能找两条线段。
分析
首先我们看一下如何判断桶能装多少水,设找到两条边ai, aj,ai < aj,则显然水不能超过容器的最短板,那么此容器的最大容积为(|i - j|)*ai。也即对于所有的容器,容积为两条线段间的距离乘以较短线段的长度。
明确了容积的求法,这道题最直观的想法就是利用嵌套循环,将所有线段两两组合成容器,并取容积的最大值,得到所需结果。但是事实证明,嵌套循环不能满足题目通过时间的限制,时间复杂度不满足需求,我们需要考虑一种时间复杂度小于O(n^2)的算法。
由于容器的容积取决于被选择的线段中较短的一个,我们可以利用这个特点,对线段进行简化筛选。假定a1, a2, ..., an,是一个数组,那么从数组的两端开始检验,假设两边ai, aj,ai < aj 且 i < j,求其容积后,因为ai < aj,那么较长边aj对于此桶的容积没有影响,因此将下标 i 下移一个位置;若ai, aj,ai > aj 且 i < j,则将下标 j 上移一个位置并继续计算桶的容积,直到 i=j 为止。这样算法就用扫描n次所有线段变成了扫描1次所有线段,大大降低了复杂度。
解答
class Solution {public: int maxArea(vector<int>& height) { int max=0; int temp; int i=0,j=height.size()-1; while(j>i){ if(height[i]<=height[j]){ temp=(j-i)*height[i]; i++; } else if(height[i]>height[j]){ temp=(j-i)*height[j]; j--; } if(temp>max) max=temp; } return max; }};
时间复杂度为O(n^2)。
阅读全文
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
- window下安装mongoDB与设置数据库路径失败解决
- Visual Studio下建立并隐式调用自己的动态链接库dll
- 30、C#里面的列表框:ListBox的使用
- 第77讲 继承与实现比较 final const
- 通过js sdk 来进行第三方登录及授权(微博,微信,qq)
- [LeetCode]--Container With Most Water
- 关于listview中是用多个布局 并使用holderView 缓存机制的问题
- 针对json的查询--alibaba的开源项目jsonq
- Spring源码分析的几篇博客
- 解决NPM使用下载慢或者无法下载的问题error
- Tablayout的使用
- socket 并发服务器 代码案例 (多进程模式)
- spring boot学习(六)---表单验证
- 进程通信之无名pipe