【Leetcode】Container with most water
2015-04-09 01:00
267 查看
【题目】
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.
【解析】
开始把题目看错了, 以为是要找最大的一样的高度的y,然后达到长度最高,但实际上是要求求一个长方形,是整个面积最大,高度取二者最小的那个
所以采用的方法是two pointers.
一个从左边扫,一个从右边扫。初始化一个数据记录当前最大值。max
乘积是: min { height[left] ,height[right] } 长:right - left
max = max{max, product}
然后还要更新左右的值,
如果左边 > 右边,那个更新右边
否则更新左边,总之更新较小的一遍
【代码】
public static int maxArea(int[] height){
int left = 0;
int right = height.length-1;
int max= 0;
while(left < right){
max = Math.max(max, Math.min(height[left], height[right])*(right - left));
if(height[left] > height[right]){
right--;
}else{
left++;
}
}
return max;
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.
【解析】
开始把题目看错了, 以为是要找最大的一样的高度的y,然后达到长度最高,但实际上是要求求一个长方形,是整个面积最大,高度取二者最小的那个
所以采用的方法是two pointers.
一个从左边扫,一个从右边扫。初始化一个数据记录当前最大值。max
乘积是: min { height[left] ,height[right] } 长:right - left
max = max{max, product}
然后还要更新左右的值,
如果左边 > 右边,那个更新右边
否则更新左边,总之更新较小的一遍
【代码】
public static int maxArea(int[] height){
int left = 0;
int right = height.length-1;
int max= 0;
while(left < right){
max = Math.max(max, Math.min(height[left], height[right])*(right - left));
if(height[left] > height[right]){
right--;
}else{
left++;
}
}
return max;
相关文章推荐
- leetcode_Container With Most Water
- 【LEETCODE】11-Container With Most Water [Python]
- [leetcode] Container With Most Water
- leetcode:Container With Most Water 【Java】
- Container With Most Water --- LeetCode
- [leetcode][two pointers] Container With Most Water
- 【LeetCode】011 Container With Most Water
- [LeetCode]Container With Most Water
- Container With Most Water -- LeetCode
- leetcode 11 -- Container With Most Water
- leetcode(11) Container With Most Water
- 【Leetcode】Container With Most Water
- [Leetcode 11, Medium] 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