zoukankan      html  css  js  c++  java
  • [LeetCode] 42. Trapping Rain Water

    [LeetCode] 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.
    

    思路

    第 i 个位置上的水量为 min(i左边height最大值,i右边height最大值) - height[i]

    最大值可以提前算出来。

    这题还有单调栈和双指针法,有空再看。

    代码

    class Solution {
    public:
        int trap(vector<int>& height) {
            int n = height.size();
            int l[n+1], r[n+1];
            int maxx = 0;
            for (int i = 0; i < n; i++) {
                maxx = max(maxx, height[i]);
                l[i] = maxx;
            }
            maxx = 0;
            int ans = 0;
            for (int i = n - 1; i >= 0; i--) {
                maxx = max(maxx, height[i]);
                r[i] = maxx;
                ans += min(l[i], r[i]) - height[i];
            }
            return ans;
    
        }
    };
    

    吐槽: 我一开始想成单调栈了,受到之前做过题的影响.
    有空找一找单调栈的题,看看区别。

    class Solution {
    public:
        int trap(vector<int>& height) {
            int n = height.size();
            int l[n+1], r[n+1];
            for (int i = 0; i < n; i++) {
                l[i] = r[i] = i;
            }
            for (int i = 1; i < n; i++) {
                while (l[i] > 0 && height[l[i]] <= height[l[l[i]-1]]) l[i] = l[l[i]-1];
            }
            for (int i = n -2; i >= 0; i--) {
                while (r[i] < n-1 && height[r[i]] <= height[r[r[i]+1]]) r[i] = r[r[i]+1];
            }
            int ans = 0;
            for (int i = 0; i < n; i++) {
                ans += min(height[l[i]], height[r[i]]) - height[i];
            }
            return ans;
    
        }
    };
    
    欢迎转载,转载请注明出处!
  • 相关阅读:
    C语言开发CGI程序的简单例子
    js收集错误信息,错误上报
    php安装pear、pecl
    (转)进程与线程的一个简单解释
    php curl 中的gzip压缩性能测试
    (转载):() { :|:& }; : # <-- 打开终端,输入这个,回车.你看到了什么??
    (转)open和fopen的区别:
    C语言中typedef
    secureCRT使用VIM 像LINUX中那样对语法高亮
    iframe与主框架跨域相互访问方法
  • 原文地址:https://www.cnblogs.com/huihao/p/15435210.html
Copyright © 2011-2022 走看看