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

[leetcode 11]Container With Most Water

2015-06-10 16:22 459 查看
1 题目:

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.

Hide Tags
Array Two Pointers

2 思路:
天资不才,只能想出O(n^2)的方法,好吧,这个闭着眼睛随意想想也能想出来。然后,一个特例就通不过了。

看了看别人的思路,有一种方法O(n)。
https://leetcode.com/discuss/11482/yet-another-way-to-see-what-happens-in-the-o-n-algorithm
详细说明见别人的解说,在草稿纸上结合着画画就出来了。

3 代码
n^2

public int maxArea(int[] height) {
int len = height.length;
int maxArea = Math.min(height[len-1],height[0])*(len-1);
for(int i = len-1; i >= 0 ; i--){
for(int j = 0; j < i; j++){
if(height[j] < height[0]) continue;
int min = Math.min(height[i],height[j]);
int temp = min * (i-j);
if(temp > maxArea){
maxArea = temp;
}
}
}
return maxArea;
}


n

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