leetcode Container with most Water
来源:互联网 发布:淘宝店铺号和旺旺号 编辑:程序博客网 时间:2024/06/10 15:39
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.
首先理解题意,求的是两条纵线和x轴组成的容器所能装水的最大容积(面积),即求max(min(ai,aj)*(j-i)),其中j>i,这道题首先需要证明一个理论,其实这个理论从直观观察还是可以看出来的,这里引用博客http://blog.csdn.net/a83610312/article/details/8548519里的证明,写的比较简洁清晰:
①: 在 j 的右端没有一条线会比它高! 假设存在 k |( j<k && ak > aj) ,那么 由 ak> aj,所以 min( ai,aj, ak) =min(ai,aj) ,所以由i, k构成的容器的容积C' = min(ai,aj ) * ( k-i) > C,与C是最值矛盾,所以得证j的后边不会有比它还高的线;
②:同理,在i的左边也不会有比它高的线;
说白了就是我们从两头开始找起往中间收缩,只找比两条边中较小的边高的边,这样得到的容积才有可能比当前的大,代码:public int maxArea(int[] height) { int left=0,right=height.length-1; int area; int max=0; while(left<right){ area=Math.min(height[left],height[right])*(right-left); if(area>max) max=area; if(height[left]<height[right]){ int k=left+1; while(k<right&&height[k]<=height[left]) k++; left=k; } else{ int k=right-1; while(k>left&&height[k]<=height[right]) k--; right=k; } } 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
- 桌面软件底层日志的一种改进设计
- SVN更改新的URL
- Java-一直弄不懂public,private,final,static的区别
- 关于mysql中无法显示中文的完美解决方案
- C++设计语言三大难点
- leetcode Container with most Water
- java_opts 参数
- 单例模式双重加锁,懒加载加锁
- TCP(一 协议)
- rem
- mysql 近日用到的一些操作
- 进制之间的转换 Java
- 第一天-HTML5新增部分标签
- 线程范围内共享变量使用ThreadLocal类详细方法