<leetcode>Container With Most Water
来源:互联网 发布:淘宝联名信用卡怎么用 编辑:程序博客网 时间:2024/05/21 08: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.
一开始想的是两个for循环遍历所有的组合找出最大值,显然不满足时间。
后来想到2个pointer靠拢的方法。container容积的定义是最小边*底边,所以从底边最大的情况开始考虑。当缩小底边,需要其中最小边变大,因此从low和high两个边里找到比较小的,并移动,直到找到一个比之前大的边,然后计算当前的容积并继续移动小边。当low>=high之后结束,然后返回最大的容积
public class Solution { public int maxArea(int[] height) { int max=(height.length-1)*minimum(height[0],height[height.length-1]); int minLine=minimum(height[0],height[height.length-1]); int low=0; int high=height.length-1; while(low<high){ if(height[low]<height[high]){ minLine=height[low]; while(low<high&&height[low]<=minLine){ low++; } if(low<high){ minLine=minimum(height[low],height[high]); if((high-low)*minLine>max){ max=(high-low)*minLine; } } } else if(height[low]>=height[high]){ minLine=height[high]; while(low<high&&height[high]<=minLine){ high--; } if(low<high){ minLine=minimum(height[low],height[high]); if((high-low)*minLine>max){ max=(high-low)*minLine; } } } } return max; } public int minimum(int a, int b){ if(a<=b){ return a; } else return b; }}
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
- 的发货他并恢复后太阳能今天就白居易
- 关于das
- <leetcode> Gas station
- 用PGCL为安卓编写有效的OpenCL代码
- Objective-C入门
- <leetcode>Container With Most Water
- c++重载ostream的实现
- 会计法开始减肥可适当分开
- Ubuntu系统下如何在不重启的情况下修改hostname
- 代码面试题:Find two smallest number of an array
- poj 1953 Team Rankings
- 软件开发流程(转载)
- Leetcode: Merge Sorted Array
- 工作日报http://www.cnblogs.com/suyang/archive/2008/05/18/1201990.html