1. 程式人生 > >LeetCode刷題筆記(十一)盛最多水的容器

LeetCode刷題筆記(十一)盛最多水的容器

題目:給定 n 個非負整數 a1a2,...,an,每個數代表座標中的一個點 (iai) 。畫 n 條垂直線,使得垂直線 i 的兩個端點分別為 (iai) 和 (i, 0)。找出其中的兩條線,使得它們與 x 軸共同構成的容器可以容納最多的水。

注意:你不能傾斜容器,n 至少是2。

解法1:暴力

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

這種計算就是迴圈巢狀遍歷,得出最大的面積;這種在leetcode是超時的;

時間複雜度:O(n^2);

空間複雜度:O(1);

解法2:

class Solution {
    public int maxArea(int[] height) {
        
        int result = 0;
        int left = 0;
	int temp = 0;
        int right = height.length-1;
        
        while(left<right){
            temp = (right-left)*Math.min(height[left],height[right]);
            result = area > result ? temp : result;
            if(height[left]<height[right]){
                left++;
            }else{
                right--;
            }
        }
        return result;  
    }
}

這裡是從兩端向中間依次計算,因為計算面積取決於兩個點低的那一個,所以把低的那一個向中間移一個位置,再計算。

時間複雜度:O(n);

空間複雜度:O(1);