面试经典150题——Day16

编程入门 行业动态 更新时间:2024-10-21 06:42:17

面试<a href=https://www.elefans.com/category/jswz/34/1769979.html style=经典150题——Day16"/>

面试经典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;}
};

更多推荐

面试经典150题——Day16

本文发布于:2023-12-06 07:57:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1666944.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:经典

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!