leetcode笔记系列 42 接雨水

给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。

 

解题思路是,找到所有柱子中最高的(记为max),然后从两边,分别向最高的柱子靠拢。遍历的过程中,需要记录当前除max外最高的柱子(记为root)。max和root之间的空间,减掉这之间的柱子高度,即为所能接雨水的数量。整个算法的时间复杂度为O(n)。

 代码如下:

public int trap(int[] height) {
  int n = height.length;
  if (n <= 2)  return 0;
  int max = -1, maxInd = 0;
  //先找最高点,确定一条边
  for (int i=0; i < n; ++i) {
    if (height[i] > max) {
      max = height[i];
      maxInd = i;
    }
  }
  int area = 0, root = height[0];
  for (int i = 0; i < maxInd; ++i) {
    if (root < height[i]){
      root = height[i]; //找次高点,确定另一条边
    }else{
      area += (root - height[i]); //在两边确定情况下,直接加上差值
    }
  }
  root = height[n - 1];
  for (int i = n - 1; i > maxInd; --i) {
    if (root < height[i]){
      root = height[i];
    }else{
      area += (root - height[i]);
    }
  }
  return area;
}

posted @ 2018-07-03 17:45  albert_ygy  阅读(135)  评论(0)    收藏  举报