LeetCode题目:42. Trapping Rain Water

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/MyCodecOdecoDecodE/article/details/78511710

LeetCode题目:42. Trapping Rain Water

原题链接:https://leetcode.com/problems/trapping-rain-water/description/

解题思路:

核心思想:

  1. 并不用直接处理水的数量,而是通过计算其他的值,间接计算水的数量。

  2. 通过计算总数量,空气的数量,条的高度总和,可得

    水的数量 = 总数量 - 空气的数量 - 条的高度总和

代码细节:

  1. 总数量可以视为maxHeight * width,为一个大矩形。
  2. 空气可分为左右部分,通过最高的条来区分。
  3. 每个空气部分可以看成多个矩形组成,每当条的高度超过之前的最大值后,都可以把这部分多出的空气矩形计算出来

坑点:

  1. ​没什么坑点,一帆风顺

代码:

int trap(vector<int>& height) {
    // sum - sumAir - sumBar = sumWater
    // sum = maxHeight * height.size()
    int sumBar = 0;
    int sumAir = 0;
    int maxHeight = 0;
    int maxHeightIndex = 0;

    // 除去左半部分Air 
    for (int i = 0; i < height.size(); i++) {
        // 更新bar总和 
        sumBar += height[i];
        // 更新Air总和 
        if (height[i] > maxHeight) {
            sumAir += i * (height[i] - maxHeight);
            // 记录最大值的下标 
            maxHeightIndex = i;
            maxHeight = height[i];
        }
    }

    maxHeight = 0;
    // 计算右半部分Air
    for (int i = height.size() - 1; i >= maxHeightIndex; i--) {
        if (height[i] > maxHeight) {
            sumAir += (height.size() - 1 - i) * (height[i] - maxHeight); 
            maxHeight = height[i];
        }
    } 

    return maxHeight * height.size() - sumAir - sumBar;
}

猜你喜欢

转载自blog.csdn.net/MyCodecOdecoDecodE/article/details/78511710