Leetcode11. Container With Most Water
Find two lines that together with the x-axis form a container, such that the container contains the most water.
双指针法: intuition 左指针向右移动遇到更高的height可以储更多的水, 即可以抵消width下降的影响, 同理右指针向左
左指针高度小于右指针 left++
else right–
class Solution {
public int maxArea(int[] height) {
int left = 0;
int right = height.length - 1;
int area = 0;
while (left < right){
area = Math.max(area,(right-left)*Math.min(height[left],height[right]));
if (height[left] < height[right]){
left++;
}
else{
right--;
}
}
return area;
}
}
Leetcode42. Trapping Rain Water
Method1:
同双指针法, 需要记录左右指针的最大height, 算储水量需要一块一块算
class Solution {
public int trap(int[] height) {
int left = 0;
int right = height.length - 1;
int leftMax = 0, rightMax = 0;
int ans = 0;
while (left < right){
leftMax = Math.max(leftMax, height[left]);
rightMax = Math.max(rightMax, height[right]);
if (leftMax < rightMax){
ans += Math.max(0, leftMax - height[left]);
left++;
}
else{
ans += Math.max(0, rightMax - height[right]);
right--;
}
}
return ans;
}
}
Method2:
dynammic programming (from brute force 对于每个i分别往左往右找最大的柱子):
- leftMax[] the maximum starting from the left
- rightMax[] the maximum starting from the right
这样对于每个 i 可以计算出低洼的面积
class Solution {
public int trap(int[] height) {
int n = height.length;
int[] left = new int[n];
int[] right = new int[n];
left[0] = height[0];
right[n-1] = height[n-1];
int result = 0;
for (int i = 1; i < n; i++){
left[i] = Math.max(height[i], left[i-1]);
}
for (int i = n-2; i >= 0; i--){
right[i] = Math.max(height[i], right[i+1]);
}
for (int i = 0; i < n; i++){
result += Math.min(left[i],right[i]) - height[i];
}
return result;
}
}