LeetCode


题目:

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.

思路:

1)两个for循环,遍历所有情况,时间O(n^2). 超时了.

package area;

public class ContainerWithMostWater {

public int maxArea(int[] height) {
int n = height.length;
int maxArea = 0;
for (int i = 0; i < n - 1; ++i) {
for (int j = i + 1; j < n; ++i) {
int area = Math.min(height[i], height[j]) * (j - i);
if (maxArea < area)
maxArea
= area;
}
}

return maxArea;
}

public static void main(String[] args) {
// TODO Auto-generated method stub

}

}

 

2)用两边夹的方式解决。设Aij为坐标(ai, aj)所圈定的区域面积,其中j > i,则Aij = min(ai, aj)*(j - i)。

     如果ai <= aj,则对于k < j,有Aik = min(ai, ak) * (k - i)。由于(k - i) < (j - i),min(ai, ak) <= min(ai, aj) ,所以Aik < Aij. 这说明,j没必要往左移,这是只能让i往右移。

     如果ai > aj,则对于k < i,有Aik = min(ak, aj) * (j - k)。由于(j - k) < (j - i),min(ak, aj) <= min(ai, aj) ,所以Aik < Aij. 这说明,i没必要往右移,这是只能让j往左移。

package area;

public class ContainerWithMostWater {

public int maxArea(int[] height) {
int n = height.length;
int maxArea = 0;
int i = 0;
int j = n - 1;
while (i < j) {
int area = Math.min(height[i], height[j]) * (j - i);
if (height[i] <= height[j])
++i;
else
--j;

if (area > maxArea)
maxArea
= area;
}

return maxArea;
}

public static void main(String[] args) {
// TODO Auto-generated method stub

}

}

 

本站声明
本文转载自:http://www.cnblogs.com/shuaiwhu/p/5047844.html     作者:Container With Most Water - NULL00     发布日期:2015/12/15     本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。


 
© 2014-2017 ITdaan.com 粤ICP备14056181号