You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).
Find two lines that together with the x-axis form a container, such that the container contains the most water.
Return the maximum amount of water a container can store.
Notice that you may not slant the container.
我的解法
暴力解:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution { publicintmaxArea(int[] height) { intmax=0; for (inti=0; i < height.length - 1; i++) { // i means left border for (intj= i + 1; j < height.length; j++) { // j means right border inty= height[i] <= height[j] ? height[i] : height[j]; intx= j - i; intvolume= x * y; max = volume > max ? volume : max; } } return max; } }
會超時。
Two Pointer:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { publicintmaxArea(int[] height) { intl=0, r = height.length - 1; intresult=0; while (l < r) { intx= r - l; inty= Math.min(height[l], height[r]); intarea= x * y; result = Math.max(area, result); if (height[l] < height[r]) { // 這邊比較難說服自己腦袋,但主要概念還是留住最大的值 l++; } else { r--; } } return result; } }