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.

思路一:暴力解法,算出每两个短板之间的装水量,结果超时。

public class Solution {
    public boolean isPalindrome(int x) {
        if(x<0)
        return false;
        if(x>=0&&x<=9){
            return true;
        }
        int m=0;
        int s=0;
        int a=x;
        while(a>0){
             m=a%10;
            a=a/10;
            s=10*s+m;
        }
        
        if(s==x){
            return true;
        }else{
            return false;
        }
    }
}
View Code

思路二:贪心策略。每次使其向最优的方向发展。初始化为最外两块板所构成的桶容量。短板不断向中间靠近,比较得出最大桶容量。

public class Solution {
    public int maxArea(int[] height) {
        int i=0;
        int j=height.length-1;
        int ans=0;
        while(i<j){
            int temp=(height[i]>height[j]?height[j]:height[i])*(j-i);
            if(temp>ans){
                ans=temp;
            }
            if(height[i]<height[j]){
                i++;
            }else{
                j--;
            }
        }
        
        return ans;
    }
}
View Code

 

posted on 2015-06-12 13:35  gone~with~wind  阅读(106)  评论(0编辑  收藏  举报