Container With Most Water

本来以为是个简单的题目,直接二重循环,结果小测试过了,大测试超时了= = 1万个数据啊,必须优化了
public class Solution {
    public int maxArea(int[] height) {
        // Start typing your Java solution below
        // DO NOT write main() function
        int max = 0;
        int area = 0;
        for (int i = 0; i < height.length - 1; ++i)
            for (int j = i + 1; j < height.length; ++j){
                area = (j-i) * Math.min(height[i], height[j]);
                if (area > max)
                    max = area;
            }
        return max;
    }
}


想了一下 如果按照“以第i条线为最短边”来遍历的话,只需要从两边分别开始找到比它长的就行了,因为高度已经定了(第i条边的长度),而宽度自然是离i越远越好
public class Solution {
    public int maxArea(int[] height) {
        // Start typing your Java solution below
        // DO NOT write main() function
        int max = 0;
        int area = 0;
        for (int i = 0; i < height.length; ++i){
            for (int j = 0; j < i; j++)
                if (height[j] >= height[i]){
                    area = height[i] * (i - j);
                    if (area > max)
                        max = area;
                    break;
                }
            for (int j = height.length - 1; j > i; j--)
                if (height[j] >= height[i]){
                    area = height[i] * (j - i);
                    if (area > max)
                        max = area;
                    break;
                }
        }
        return max;
    }
}

你可能感兴趣的:(contain)