題目描述:
給你 n 個非負整數 a1,a2,...,an,每個數代表座標中的一個點 (i, ai) 。在座標內畫 n 條垂直線,垂直線 i 的兩個端點分別爲 (i, ai) 和 (i, 0)。找出其中的兩條線,使得它們與 x 軸共同構成的容器可以容納最多的水。
說明:你不能傾斜容器,且 n 的值至少爲 2。
思路分析:這題最容易想到的就是暴力解法,兩個for循環搞定,時間複雜度爲O(n2)
但其實可以利用雙指針法,使時間複雜度爲O(n),注意到這兩個特點:1、相同情況下,兩邊距離越遠越好
2、區域大小受限於最短邊於是 當左邊較短時,應移動左邊 ; 右邊較短時,應移動右邊; 兩邊相等,則兩邊皆可移動。
代碼實現:
public class Solution4 { int max = 0; //暴力解法 public static int maxArea(int[] height) { for(int i = 0; i < height.length ; i++){ for(int j = i+1 ; j < height.length ; j++){ int temp = Math.min(height[i],height[j]) * (j - i); max = Math.max(temp,max); } } return max; } }
public class Solution4 { //雙指針解法 public static int maxArea(int[] height) { int l = 0; int r = height.length - 1; int max = Math.min(height[l], height[r]) * (r - l); while (l < r) { int temp = Math.min(height[l], height[r]) * (r - l); max = Math.max(max, temp); if (height[l] < height[r]) { l++; } else if (height[l] > height[r]) { r--; } else { l++; r--; } } return max; }