您的位置:首页 > 编程语言 > Java开发

LeetCode : Container With Most Water [java]

2016-03-05 20:53 417 查看
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.

思路:高度矮的是短板,从两端向中间搜索。

高的那一端向中间移动没有意义,因为计算面积的高不变(为矮的那端,或者高的那端变得比矮的那端更矮),而宽(j-i)却减少了,面积不可能增加。

因此,哪端矮就向中间搜索。

public class Solution {
public int maxArea(int[] height) {
int size = height.length;
int left = 0, right = size - 1;
int max = 0;
while (left < right) {
int minheight = height[left] < height[right] ? height[left] : height[right];
int tmp = minheight * (right - left);
max = max > tmp ? max : tmp;
if (height[left] < height[right])
left++;
else
right--;
}
return max;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: