1 题目:

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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)。
详细说明见别人的解说,在草稿纸上结合着画画就出来了。
 
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;
    }