Java數組內求兩數之間最大容積

leetcode學習

題目連接:https://leetcode-cn.com/problems/container-with-most-water/
在這裏插入圖片描述javascript

初解:

public static int maxArea(int[] height) {
    int max = 0;
    int length = height.length;
    for (int i = 0; i < length; i++) {
        for (int j = length-1; j >i; j--) {
            int temp = (height[i] > height[j] ? height[j] : height[i]) * (j - i);
            max = max > temp ? max : temp;
        }
    }
    return max;
}
利用嵌套循環, 指定下標i從左側開始右移,下標j從右側開始左移,每次計算兩數之間最大溶劑

優解:

public static int maxArea(int[] height) {
    int max = 0;
    int left = 0;
    int right = height.length - 1;
    while (left < right) {
        int temp = (height[left] > height[right] ? height[right] : height[left]) * (right - left);
        max = max > temp ? max : temp;
        if (height[left] > height[right])
            right--;
        else
            left++;
    }
    return max;
}
從初階解法進階而來,一樣是定位左右兩個端點,左端點小則左端點右移,右端點小則右端點左移,將本來的複雜度從O(2n)下降到O(n)
相關文章
相關標籤/搜索