题解 | #接雨水问题#
接雨水问题
https://www.nowcoder.com/practice/31c1aed01b394f0b8b7734de0324e00f
直接用快慢指针轻松解决(慢指针i;快指针j),避免用while...
public class Solution {
public long maxWater(int[] height) {
if (height.length <= 2)
return 0;
int n = height.length,res = 0;
for (int i = 1; i < n - 1; i++) {
int l_max = 0, r_max = 0;
// 找右边最高的bar;
for (int j = i; j < n; j++)
r_max = Math.max(r_max, height[j]);
// 找左边最高的bar;
for (int j = i; j >= 0; j--)
l_max = Math.max(l_max, height[j]);
// (注意:如果自己就是最高的话,
// l_max / r_max == height[i])
res += Math.min(l_max, r_max) - height[i];
}
return res;
}
}
360集团公司氛围 407人发布