11, filled most water containers

1, title

Here Insert Picture Description

2. Solution

2.1 Violence Act

The starting point and end point of all possibilities listed, and the calculated value, and to find the maximum value.
Rule calculation: Math.min (start, end) * (ji);

class Solution {
    public int maxArea(int[] height) {
        int len = height.length;
        int maxVal = 0;
        for (int i = 0; i < len; i++)
            for (int j = i + 1; j < len; j++) {
                maxVal = Math.max(maxVal, Math.min(height[i], height[j]) * (j - i));
            }
        return maxVal;
    }
}

Time complexity of O (n ^ 2) (of the n * (n-1) / 2 calculated from), the spatial complexity of O (1)

Finger 2.2 pairs

minVal * (ji), not only to ensure a length long enough, but also to ensure that the width is long enough, so use your double pointer from both sides counted, so (JI) long enough to ensure that the width is long enough, then the width of the small side due to a large movement of the side in the width.

class Solution {
    public int maxArea(int[] height) {
        int i = 0, j = height.length - 1, maxVal = 0;
        // 至少两条
        while (j > i) {
            maxVal = Math.max(maxVal, Math.min(height[i], height[j]) * (j - i));
            if (height[i] > height[j]) {
                --j;
            } else {
                ++i;
            }
        }
        return maxVal;
    }
}

Time complexity of O (n), the spatial complexity is O (1)

Published 23 original articles · won praise 0 · Views 218

Guess you like

Origin blog.csdn.net/wuprogrammer/article/details/104108824