您的位置:首页 > 大数据 > 人工智能

【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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: