题目 :container-with-most-water
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.
理解:随机给了一个数据表示高度,序号表示横坐标。确定两条线和X轴所成的木桶体积最大。
思路:
1.暴力算法,O(n^2),时间不过关
2. 贪心算法(只求当前更好的解,不考虑全局)
两边设立指针ij 从两侧向中间逼近,若左边矮,向右移,若右边矮小向左移。(最短板效应)
代码:
public class Solution {
public int maxArea(int[] height) {
int i=0,j=height.length-1,v=0,v_max=0;
while(i<j){
v=Math.min(height[i],height[j])*(j-i);
v_max=Math.max(v,v_max);
if(height[i]<height[j])
{
i++;
}
else
{
j--;
}
}
return v_max;
}
}