面试经典150题——Day16

文章目录

    • 一、题目
    • 二、题解

一、题目

42. Trapping Rain Water

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

Example 1:

Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.
Example 2:

Input: height = [4,2,0,3,2,5]
Output: 9

Constraints:

n == height.length
1 <= n <= 2 * 104
0 <= height[i] <= 105

题目来源: leetcode

二、题解

1.暴力解法

按列统计需要接的雨水的数量,最后一个用例会超时。

class Solution {
public:
    int trap(vector<int>& height) {
        int n = height.size();
        if(n <= 2) return 0;
        int res = 0;
        for(int i = 1;i < n - 1;i++){
            int h1 = 0,h2 = 0;
            for(int j = i;j >= 0;j--) h1 = max(h1,height[j]);
            for(int j = i;j < n;j++) h2 = max(h2,height[j]);
            res += min(h1,h2) - height[i];
        }
        return res;
    }
};

2.对左边最大高度和右边最大高度进行初始化

时间复杂度缩减为O(n)

class Solution {
public:
    int trap(vector<int>& height) {
        int n = height.size();
        if(n <= 2) return 0;
        int res = 0;
        vector<int> leftMax(n,0);
        vector<int> rightMax(n,0);
        leftMax[0] = height[0];
        rightMax[n-1] = height[n-1];
        for(int i = 1;i < n - 1;i++) leftMax[i] = max(height[i],leftMax[i - 1]);
        for(int i = n - 2;i > 0;i--) rightMax[i] = max(height[i],rightMax[i + 1]);
        for(int i = 1;i < n - 1;i++) res += min(leftMax[i],rightMax[i]) - height[i];
        return res;
    }
};

你可能感兴趣的:(算法,leetcode,数据结构,c++,双指针)