zoukankan      html  css  js  c++  java
  • [LeetCode]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 is able to trap after raining.

    For example, 
    Given [0,1,0,2,1,0,1,3,2,1,2,1], return 6.

    题目解析:

    遍历数组,找到当前元素左边的最大值max_left右边的最大值max_right,如果min(max_left, max_right) < 当前元素高度h,将h - min(max_left, max_right)加到结果上去。

     1 class Solution {
     2 public:
     3     int trap(vector<int>& height) {
     4         int length = height.size();
     5         vector<int> max_left(length, 0);
     6         vector<int> max_right(length, 0);
     7         
     8         int result = 0;
     9         
    10         for (int i = 1; i < length; ++i) {
    11             max_left[i] = max(max_left[i - 1], height[i - 1]);
    12             max_right[length - 1 - i] = max(max_right[length - i], height[length - i]);
    13         }
    14         
    15         for (int i = 0; i < length; ++i) {
    16             int h = min(max_left[i], max_right[i]);
    17             if (h > height[i]) {
    18                 result += (h - height[i]);
    19             }
    20         }
    21         
    22         return result;
    23     }
    24 };
  • 相关阅读:
    纪念日给男(女)朋友的表白页面
    Vue组件的传值(非父子之间)
    express脚手架的安装和使用
    MongoDB数据库
    vuex状态
    MVVM框架的简单理解
    关于vue脚手架
    申请百度密钥
    svg
    微信小程序开发学习笔记
  • 原文地址:https://www.cnblogs.com/skycore/p/4868909.html
Copyright © 2011-2022 走看看