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

Leetcode-container-with-most-water

2016-06-27 16:39 351 查看


题目描述

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 linei 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.

我采用的就是暴力搜索的方法,复杂度o(n^2),感觉不是太好。

public static int maxArea(int[] height) {
int max = -1;
int res = 0;
for(int i=0; i<height.length-1; i++){
for(int j=i+1; j<height.length; j++){
if(height[i] >= height[j]){
res = height[j] * (j-i);
}else{
res = height[i] * (j-i);
}
if(res > max)
max = res;
}
}
return max;
}

看了一下别人的做法,用贪心算法解决,感觉是好一些。

public static int maxArea(int[] height) {
int result=0;
if(height.length<=1) return result; //无法构成容器
int i=0,j=height.length-1;
while(i<j){
int area = (j-i)*Math.min(height[i],height[j]);
if(area>result)result = area;
if(height[i]>height[j]){
j--;
}else{
i++;
}

}
return result;
}
合理性解释:当左端线段L小于右端线段R时,我们把L右移,这时舍弃的是L与右端其他线段(R-1, R-2, ...)组成的木桶,这些木桶是没必要判断的,因为这些木桶的容积肯定都没有L和R组成的木桶容积大。


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