題目連接:https://leetcode.com/problems/container-with-most-water/description/數組
題目大意:給出一串數組(a1, a2, a3, ...an),表示座標(i, ai),一樣表示一條直線是從(i, 0)到(i, ai),從中選出兩條直線,計算其容器能蓄水多少,並找出最多的蓄水量。(容器不能傾斜,就是兩條直線能夠是不一樣高度,可是蓄水量要按照低高度的那條直線來計算),例子以下:ide
法一:暴力,對於一條直線,分別遍歷左邊和右邊直線,計算其蓄水量,取最大者。惋惜超時了。代碼以下:spa
1 public int maxArea(int[] height) { 2 int res = 0; 3 for(int i = 0; i < height.length; i++) { 4 //計算左邊直線 5 for(int j = height.length - 1; j > i; j--) { 6 if(height[j] >= height[i]) { 7 res = Math.max(res, (j - i) * height[i]); 8 break; 9 } 10 } 11 //計算右邊直線 12 for(int j = 0; j < i; j++) { 13 if(height[j] >= height[i]) { 14 res = Math.max(res, (i - j) * height[i]); 15 break; 16 } 17 } 18 } 19 return res; 20 }
法二:兩指針移動,與42題的兩指針移動相似但略有區別,左指針與右指針相比較,記錄較大者,若左指針較小,則從左往右移動,若右指針較小,則從右往左移動,若是當前值比較大者大,則計算:(較大者下標-當前值下標)*當前值高度,計算獲得最後的結果。代碼以下(耗時8ms):指針
1 public int maxArea(int[] height) { 2 int res = 0, left = 0, right = height.length - 1; 3 while(left < right) { 4 //若是左指針<=右指針 5 if(height[left] <= height[right]) { 6 while(left < right && height[left] <= height[right]) { 7 res = Math.max(res, (right - left) * height[left++]); 8 } 9 } 10 //若是左指針>右指針 11 else { 12 while(left < right && height[left] > height[right]) { 13 res = Math.max(res, (right - left) * height[right--]); 14 } 15 } 16 } 17 return res; 18 }