Both are Two Pointers
11. Container With Most Water
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| public int maxArea(int[] height) { int i = 0; int j = height.length-1; int res = 0; while(i < j){ //面积 int tmp = (j-i) * Math.min(height[i], height[j]); res = Math.max(res, tmp); if(height[i] > height[j]){ j--; }else{ i++; } } return res; }
|
42. Trapping Rain Water
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| public int trap(int[] height) { int i = 0; int j = height.length - 1; //记录当前最大高度 int curh = 0; //记录每个值的高度 int[] res = new int[height.length]; while (i <= j) { if (height[i] > height[j]) { // curh = Math.max(curh, height[i]); curh = Math.max(curh, height[j]); res[j] = curh; j--; } else if (height[i] < height[j]) { curh = Math.max(curh, height[i]); res[i] = curh; i++; } else { curh = Math.max(curh, height[i]); res[i] = curh; res[j] = curh; i++; j--; } } int cnt = 0; for (int k = 0; k < height.length; k++) { cnt += (res[k] - height[k]); } return cnt; }
|
More Reference
11. Container With Most Water
42. Trapping Rain Water