LeetCode面试题 17.21 直方图的水量

[复制链接]
发表于 2025-9-18 06:59:53 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
题目
解答
  1. package leetcode.editor.cn;
  2. //leetcode submit region begin(Prohibit modification and deletion)
  3. class Solution {
  4.     public int trap(int[] height) {
  5.         int length = height.length;
  6.         if (length == 0) {
  7.             return 0;
  8.         }
  9.         int[] leftMax = new int[length];
  10.         leftMax[0] = 0;
  11.         for (int i = 1, end = length - 1; i < end; ++i) {
  12.             leftMax[i] = Math.max(leftMax[i - 1], height[i - 1]);
  13.         }
  14.         int[] rightMax = new int[length];
  15.         rightMax[length - 1] = 0;
  16.         for (int i = length - 2; i >= 0; --i) {
  17.             rightMax[i] = Math.max(rightMax[i + 1], height[i + 1]);
  18.         }
  19.         int result = 0;
  20.         for (int i = 1, end = length - 1; i < end; ++i) {
  21.             if (leftMax[i] > height[i] && rightMax[i] > height[i]) {
  22.                 result += Math.min(leftMax[i], rightMax[i]) - height[i];
  23.             }
  24.         }
  25.         return result;
  26.     }
  27. }
  28. //leetcode submit region end(Prohibit modification and deletion)
复制代码
测试用例
  1. package leetcode.editor.cn;
  2. import org.junit.Assert;
  3. import org.junit.Test;
  4. public class SolutionTest {
  5.     public SolutionTest() {
  6.     }
  7.     @Test
  8.     public void test() {
  9.         Solution s = new Solution();
  10.         int result = s.trap(new int[]{0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1});
  11.         Assert.assertTrue(String.valueOf(result), result == 6);
  12.     }
  13. }
复制代码
本题目初看之下照旧有点唬人的,一下子想不到解答的方法。
把题目分解为两个题目:


  • 指定坐标的位置,能不能盛水。
  • 假如上个命题建立,那么能装多少水。
第一个题目从知识出发,很好解答,即凹进去的位置,才华装水;比周边高的位置,肯定不能装水。
第二个题目,对于能装水的点,装多少水,取决于周边的最小高度,然后减去自身的高度,便是当前坐标点可以盛的水。
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表