面试题 17.21. 直方图的水量(Interview question 17.21 Water volume of histogram)-其他

面试题 17.21. 直方图的水量(Interview question 17.21 Water volume of histogram)

class Solution {
public int trap(int[] height) {
if (height == null || height.length <= 2) {
return 0;
}
int ans = 0;
int leftMax = height, rightMax = height[height.length - 1];
int left = 1, right = height.length - 2;
while (left <= right) {
if (leftMax < rightMax) {
ans += Math.max(leftMax - height[left], 0);
leftMax = Math.max(leftMax, height[left++]);
} else {
ans += Math.max(rightMax - height[right], 0);
rightMax = Math.max(rightMax, height[right--]);
}
}
return ans;
}
}
————————

Given a histogram (also known as histogram), suppose someone pours water continuously from it, how much water can the histogram store in the end? The width of the histogram is 1.

Source: leetcode

class Solution {
public int trap(int[] height) {
if (height == null || height.length <= 2) {
return 0;
}
int ans = 0;
int leftMax = height, rightMax = height[height.length - 1];
int left = 1, right = height.length - 2;
while (left <= right) {
if (leftMax < rightMax) {
ans += Math.max(leftMax - height[left], 0);
leftMax = Math.max(leftMax, height[left++]);
} else {
ans += Math.max(rightMax - height[right], 0);
rightMax = Math.max(rightMax, height[right--]);
}
}
return ans;
}
}