[LeetCode] 42. Trapping Rain Water

从机械到数字:EC11旋转编码器与ESP32的PWM控制艺术 本文详细解析了EC11旋转编码器与ESP32的PWM控制技术,探讨了如何将机械旋转动作转换为精确的数字信号控制。通过硬件连接、信号处理和软件优化等实践技巧,开发者可以构建高效的人机交互系统,适用于智能照明、电机控制等多种应用场景。 阅读详情

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.
在这里插入图片描述

Example:
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6

解析

给出一个数组,计算出储水量,如上图所示。

解法1:暴力

对每一个点,往左搜索出左边的最大高度,往右搜索出右边的最大高度,得到当前点的储水量为二者高度较小着减去当前高度。

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

解法2:动态规划

根据解法1的思想,一开始我是想用两个数组,分别表示当前点的左边最大高度和右边最大高度,这样的话需要三次遍历和两倍空间。
后面看了大神解法,只需要开一个数组就行了,先从左往右扫,获得左边的的最大高度,然后从右往左扫,获取右边的最大高度,然后与当前数组中最大的左边高度相比,取较小值,如果较小值大于当前高度,则加上当前储水量。

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

解法3:双指针

同样是借助解法1的思想,使用left和right两个指针,并且设置maxleft和maxright两个值分别表示左边最大值和右边最大值。

  • 初始化left=0,right=size-1, maxleft = maxright = 0;
  • 当left<right时:
    如果height[left]<=height[right]: 更新maxleft = max(maxleft,height[left]), 判断是否要加入差值,left++。
    否则,同理,right–。
class Solution {
public:
    int trap(vector<int>& height) {
        int size = height.size();
        int ans = 0;
        int maxleft = 0;
        int maxright = 0;
        int left =0, right = size-1;
        while(left < right){
            if(height[left] <= height[right]){
                maxleft = max(maxleft, height[left]);
                if(maxleft > height[left])
                    ans += maxleft- height[left];
                left ++;
            }
            else{
                maxright = max(maxright, height[right]);
                if(maxright > height[right])
                    ans += maxright - height[right];
                right --;
            }
        }
        return ans;
    }
};

解法4:栈stack

利用单调栈,维持一个单调递减栈,栈中保存的元素是下标,保证下标对应的高度呈单调递减。
当栈不为空,当前高度大于栈顶时,先判断栈的大小是否大于2,如果小于2则直接break,否则计算距离和边界高度,得到储水量。
当前高度小于或者等于栈顶时,直接压栈。

class Solution {
public:
    int trap(vector<int>& height) {
        int size = height.size();
        int i=0, ans=0;
        stack<int> st;
        while(i < size){
            while(!st.empty() && height[i] > height[st.top()]){
                int top = st.top();
                st.pop();
                if(st.empty())
                    break;
                int distance = i - st.top() -1;
                int bound = min(height[i], height[st.top()]) - height[top];
                ans += distance*bound;
            }
            st.push(i);
            i++;
        }
        return ans;
    }
};

参考

https://leetcode.com/problems/trapping-rain-water/submissions/
http://www.cnblogs.com/grandyang/p/4402392.html

ISO15118-20证书结构关系解读(7.3.2.1) 本文主要讲述ISO15118-20:2022标准所有证书结构的关联关系,目的是为后续基于ISO15118-20车桩通讯及PNC充电等提供基础支撑。 本文所有的证书关系图全部来源于ISO15118-20:2022标准规范,在后续的讲解过程会将图的摘取出处给提供出来,便于后期文章和标准对应起来解读。 阅读详情

相关推荐

【电子元件篇】MOSFET场效应管作用、选型和测量指南-超简单解读

场效应管是一种电压控制型半导体器件,相比三极管具有输入阻抗高、噪声小、功耗低等优势。主要分为结型和绝缘栅型两大类,后者又可分为耗尽型和增强型MOS管。场效应管通过栅极电压控制漏极电流,具有转移特性和输出特性两大静态特性,以及快速的开关特性。其关键参数包括饱和漏源电流、夹断电压、跨导等,应用场景涵盖信号放大、恒流源、阻抗变换等领域。使用时需根据电路需求选择合适类型,如结型管适合一般放大,功率MOSFET适合高压大电流场合。检测时可用万用表电阻档初步判断好坏和放大能力。

2301_81299416的博客 2540

【LeetCode】42. Trapping Rain Water【双指针&栈】

n个非负整数,数值代表高度,问这样的形状能收集多少雨水。原题的图片有助于理解题意。 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. The...

zhaoqinmuxue的博客 713

Proteus 8.9仿真五路抢答器:从74LS148编码到NE555报警的保姆级电路拆解

本文详细解析了使用Proteus 8.9仿真五路抢答器的完整设计流程,从74LS148优先编码器到NE555定时报警电路。通过保姆级的电路拆解和芯片选型指南,帮助读者掌握数字电路中的编码、锁存、译码和定时等核心技术,实现稳定可靠的抢答系统仿真。

weixin_30836759的博客 380

LeetCode-42-Trapping Rain Water 贪心或单调栈

这个题一开始想麻烦了,我用单调栈实现了一下,A了,但是只打败了0.4%的人,后来看了一眼别人的博客,发现没那么麻烦,找到最高点,从左右贪心就行了。。。 下面是两份不同做法的代码,时间复杂度都是O(n) class Solution(object): def trap(self, height): """ :type height: List[in

世靖的码场 927

使用TBtools进行物种间共线性分析

Sequence Toolkit ---Fasta Tools ----ID Prefix (fasta文件)

sunny_dayone的博客 8743

PMP–一、二、三模–分类–13.干系人管理

A:确认是否已制定沟通管理计划,使业务干系人认识到项目的成功之处。B:让业务干系人参加冲刺回顾会议。C:与发起人和关键干系人一起确定产品待办事项列表中的优先要务,以便交付商业利益。D:为关键干系人开展收尾调研。C。

stqer的博客 1417

LeetCode42——Trapping Rain Water

LeetCode42——Trapping Rain Water 题意: 看图就很明显。 但是做起来就没想象的简单了。。。 我最初的疑惑: 如果序列是这种情况01010,也就是说“凹点”两边都是“凸点”这样就简单了,直接根据短板原理可求,遍历求出索引为i-1和i+1的value的最小值即可。。。 但是如果遇到这种情况21012,也就是中间0的凹点,两边的壁呈递增,就懵逼了。。。

上善若水 1984

[deprecated]第九章:SVM机制: 9-2 Linux HMM原理与实现详解

Linux内核HMM(异构内存管理)子系统为异构计算平台提供统一内存管理机制,支持CPU与GPU等设备共享虚拟地址空间,实现零拷贝数据访问。其核心功能包括:1)统一虚拟地址空间,设备可直接访问CPU进程内存;2)实时页表同步与失效通知,确保地址空间一致性;3)支持设备端page fault处理;4)管理多种内存类型(系统内存、设备私有内存等)。HMM通过mmu_interval_notifier机制感知地址空间变化,提供标准API简化驱动开发,显著提升异构计算性能和数据传输效率。

图形/计算GPU的驱动与虚拟化技术分享园地 2538

LeetCode42. Trapping Rain Water

LeetCode42. Trapping Rain Water

bookman的博客 507

Android UI 组件系列(二):Button 进阶用法

在这篇博客中,我们深入探讨了 Button 的进阶用法,重点介绍了如何通过 事件处理 来响应用户的操作,如何使用 自定义样式 来提升按钮的外观,并利用 StateListDrawable 来管理按钮在不同状态下的表现。这些技巧能够帮助你打造更具交互性、视觉吸引力和动态响应的按钮,提升用户体验。

weixin_39339407的博客 1625

结构优化软件:OptiStruct_(11).拓扑优化

在OptiStruct中,设计空间可以通过定义设计区域来实现。设计区域是结构中可以进行材料变化的部分。几何区域:通过几何选择工具选择特定的区域。网格区域:通过网格选择工具选择特定的单元。假设我们有一个简单的梁结构模型,网格文件为beam.fem。我们希望在梁的中部进行拓扑优化,以减轻重量并保持刚度。

kkchenjj的博客 1367

LeetCode 42. Trapping Rain Water(Hard)

查看原文,请点击彼得.攀的小站 查阅更多的题解,请点击 Problem 42. Trapping Rain Water(Hard) 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 tra...

彼得.攀的blog 381

基于信号完整性的PCB设计原则

基于信号完整性的PCB设计建议,以单网络的信号布线作为评估对象,给出了一些最基础的设计指导,如何灵活运用,取决于设计者根据实际场景如何做取舍和判断。

一只豌豆象的博客 1758

LeetCode 42. Trapping Rain Water--算法题--c++解法

LeetCode 42. Trapping Rain Water–c++解法 LeetCode题解专栏:LeetCode题解 我做的所有的LeetCode的题目都放在这个专栏里,大部分题目Java和Python的解法都有。 Given n non-negative integers representing an elevation map where the width of each ba...

个人博客 928

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

Leetcode-42. Trapping Rain Water [C++][Java]

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.

贫道绝缘子的博客 632

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

Leetcode-42.-Trapping-Rain-Water

title:Leetcode 42. Trapping Rain Water 1. 问题描述 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. ...

qzylala的博客 184

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Leetcode1-100: 42. Trapping Rain Water

Leetcode1-100: 42. Trapping Rain Water问题描述解题思路1. 统计横向的格子数量2. 统计每一列的储水量3. 利用动态规划来改进思路2代码实现implement 1implement 2implement 3分析后记 问题描述 Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is a

Y123iwantit的博客 299

python写算法题:leetcode: 42. Trapping Rain Water

class Solution(object): def swap(self, items, ind, i, j): tmp=items[i] items[i]=items[j] items[j]=tmp tmp=ind[i] ind[i]=ind[j] ind[j]=tmp def q...

277

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 is able to trap after raining. The above elev...

Wisimer 203

LeetCode 42: Trapping Rain Water 解题与思考

LeetCode 42: Trapping Rain Water 解题与思考[原题链接]题目描述给出一个数列ana_n,代表一连串的障碍的高度,求下雨时能够困住的水的体积思路我们从左开始遍历数组,先记录当前最高的障碍物,当找到一个更高的障碍物时,这中间就会有水困住。 但是这么做的话,会有可能在找到一个最高的障碍物之后,后面有一个次高的障碍物,这两个障碍物之间也困住了水,但是因为算法问题,这段水没算

码农a嘘的博客 325

Leetcode: 42. Trapping Rain Water

Leetcode: 42. Trapping Rain Water

qq_16318319的博客 269

leetcode 42 Trapping Rain Water

Trapping Rain Water Total Accepted: 47928 Total Submissions: 158168 Difficulty: Hard Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how mu

javays1的专栏 601

Leetcode 42. Trapping Rain Water (Hard) (cpp)

Leetcode 42. Trapping Rain Water (Hard) (cpp)

还是需要多学习!闷声大发财,这是坠吼的! 543

LeetCode 42. Trapping Rain Water 题解

本题是双指针和动态规划的经典应用问题,主要考察对这两种算法思想的理解和使用。通过使用动态规划或双指针,我们可以高效地计算能接的雨水量。动态规划的核心思想是:对于每个柱子,其能接的雨水量取决于其左侧和右侧的最大高度。双指针的核心思想是:使用两个指针分别指向数组的开始和结束位置,根据左侧和右侧的最大高度来移动指针,计算能接的雨水量。在实际应用中,双指针方法通常更受欢迎,因为它的空间复杂度更低,只需要常数级的额外空间。这种方法不仅适用于接雨水问题,还可以应用于许多其他需要计算两侧最大高度的问题。

cannonjinx的博客 4238

LeetCode Top 100 Liked Questions 42. Trapping Rain Water (Java版; Hard)

welcome to my blog LeetCode Top 100 Liked Questions 42. Trapping Rain Water (Java版; Hard) 题目描述 Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how...

littlehaes的博客 178

[LeetCode]42. Trapping Rain Water

[LeetCode]42. Trapping Rain Water题目描述思路维护一个栈 先将数组中第一个元素入栈, 后续元素和栈顶元素做比较, 若小于栈顶元素,则入栈,继续循环 若大于栈顶元素,则栈顶元素出栈,计算增加的数目,保留当前栈顶元素值 重复与栈顶元素比较,直到满足小于条件或栈中元素为空举例来说 对于 heights = {2,1,0,1,3} 开始将2入栈,此时栈中元素为{

Lcharon的博客 343
上一篇: [LeetCode] 41. First Missing Positive
下一篇: [LeetCode] 43. Multiply Strings
Peng_maple
博客等级 码龄10年 0粉丝 79原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值