【LeetCode】Container With Most Water
2014-03-11 14:30
281 查看
Container With Most Water
Total Accepted: 6700 Total Submissions: 22080 My Submissions
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.
题目大意是求解两条木板和横轴组成的空间,可以装最多的水,图形化表示就是这样子:
![](http://img.blog.csdn.net/20140311142826843?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMzAyNzk5Ng==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
解题思路类似Two Sum,有两个指针,从头和尾向中间靠近,假设这两个指针为low和high。
当指针在头和尾的时候,其实这个时候长度最长,但是高度取决于Math.min(A[low],A[high])。
往中间走的话,长度会减小,但是高度有可能增高。
如果还有面积最大值的话,并且高度只能向Math.max(A[low],A[high])靠近,那么只能在low+1到high或者low到high-1之间。
当然也可以暴力搜索,时间复杂度为O(N*N),大数据的话必然超时。
Java AC
Total Accepted: 6700 Total Submissions: 22080 My Submissions
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.
题目大意是求解两条木板和横轴组成的空间,可以装最多的水,图形化表示就是这样子:
解题思路类似Two Sum,有两个指针,从头和尾向中间靠近,假设这两个指针为low和high。
当指针在头和尾的时候,其实这个时候长度最长,但是高度取决于Math.min(A[low],A[high])。
往中间走的话,长度会减小,但是高度有可能增高。
如果还有面积最大值的话,并且高度只能向Math.max(A[low],A[high])靠近,那么只能在low+1到high或者low到high-1之间。
当然也可以暴力搜索,时间复杂度为O(N*N),大数据的话必然超时。
Java AC
public class Solution { public int maxArea(int[] height) { int len = height.length; int max = 0; int low = 0; int high = len-1; while(low < high){ int area = (high - low) * Math.min(height[low], height[high]); max = Math.max(area, max); if(height[low] <= height[high]){ low++; }else{ high--; } } return max; } }
相关文章推荐
- 010_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(using Python)
- [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-11 Container With Most Water
- LeetCode Container With Most Water
- 【leetcode刷提笔记】Container With Most Water
- leetcode-Container With Most Water
- Leetcode 11: Container With Most Water
- LeetCode 011 Container With Most Water
- leetcode011 Container With Most Water