动态规划
木桶效应 - 底座高度
动态规划?还是不懂这怎么就是动态规划了~
两个数组:
- leftMax :每个位置的左侧 max
- rightMax:每个位置的右侧 max
/**
* 动态规划的实现 (这就叫动态规划吗?)
* @param height 数组
* @return 雨量
*/
public int trap(int[] height) {
final int length = height.length;
// 左侧最大值
int[] lm = new int[length];
// 右侧最大值
int[] rm = new int[length];
lm[0] = height[0];
rm[length - 1] = height[length - 1];
for (int i = 1; i < length; i++) {
lm[i] = Math.max(height[i], lm[i - 1]);
}
for (int i = length - 2; i >= 0; i--) {
rm[i] = Math.max(height[i], rm[i + 1]);
}
System.out.println(Arrays.toString(lm));
System.out.println(Arrays.toString(rm));
int ans = 0;
for (int i = 0; i < height.length; i++) {
ans = ans + Math.min(lm[i], rm[i]) - height[i];
}
return ans;
}
单调栈
单调栈、单调递减
我理解的是“计算凹槽的体积”,找到所有的凹槽~
凹槽的特点:先递减,再递增
还是不是很理解~
三维
water[i][j] =
max(
heightMap[i][j],
min(water[i−1][j],water[i+1][j],water[i][j−1],water[i][j+1])
)
图上的公式错了呀~
if (heightMap.length <= 2 || heightMap[0].length <= 2) {
return 0;
}
int m = heightMap.length;
int n = heightMap[0].length;
boolean[][] visit = new boolean[m][n];
PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(o -> o[1]));
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (i == 0 || i == m - 1 || j == 0 || j == n - 1) {
pq.offer(new int[]{i * n + j, heightMap[i][j]});
visit[i][j] = true;
}
}
}
int res = 0;
int[] dirs = {-1, 0, 1, 0, -1};
while (!pq.isEmpty()) {
int[] curr = pq.poll();
for (int k = 0; k < 4; ++k) {
int nx = curr[0] / n + dirs[k];
int ny = curr[0] % n + dirs[k + 1];
if (nx >= 0 && nx < m && ny >= 0 && ny < n && !visit[nx][ny]) {
if (curr[1] > heightMap[nx][ny]) {
res += curr[1] - heightMap[nx][ny];
}
pq.offer(new int[]{nx * n + ny, Math.max(heightMap[nx][ny], curr[1])});
visit[nx][ny] = true;
}
}
}
return res;