LeetCode_直方图最大面积(Largest Rectangle in Histogram)

LeetCode: Largest Rectangle in Histogram(直方图最大面积) 具体的题目描述为: Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram. Above is a histogram wher 阅读详情

一、题目

Given n non-negative integers representing the histogram’s bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.

Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].

The largest rectangle is shown in the shaded area, which has area = 10 unit.

For example,Given height = [2,1,5,6,2,3],return 10.

1.1.1

LeetCode 84题:Largest Rectangle in Histogram,给定一个直方图(下图a),求直方图中能够组成的所有矩形中,面积最大为多少。对于图a来说,我们很容易看出来面积最大的矩形为高度为5和6的直方图组成的矩形(图b隐形部分),其面积为5 * 2 = 10。


二、解题

1.感想

如果就对于图片的示例而言,许多人一看就知道答案了,压根就不需要太多的思考,可是正是因为这种定性的思考,让我们慢慢没法“知其所以然”,也让我们慢慢失去了举一反三的思考方式,就图片的示例而言,之所以我们一看就能看出答案,是因为示例的例子数据太少了,如果数据很多的时候我们能一看就看出答案吗?所以无论面对什么样的题目,我们都不能放弃“知其所以然”,从根本解决问题。

2.暴力搜索

这道题目一个显而易见的解决方法就是暴力搜索:找出所有可能的矩形,然后求出面积最大的那个。要找出所有可能的矩形,只需要从左到右扫描每个立柱,然后以这个立柱为矩形的左边界(假设为第i个),再向右扫面,分别以(i+1, i+2, n)为右边界确定矩形的形状。

这符合我们本能的思考过程:要找出最大的一个,就先列出所有的可能,比较大小后求出最大的那个。然而不幸的是,本能的思考过程通常是简单粗暴而又低效的,就这个题目来说,时间复杂度为N^2 。

3.使用动态规划

用left[i]表示第i个柱子可以最多向左延伸至第left[i]个柱子,形成一个矩形,right[i]则表示向右延伸。遍历两次,分别计算出这两个数组。

再遍历一次,即可求出所有的柱子可以形成的最大的矩形面积。为了减少边界的判断,可以使用哨兵,在两端添加两个柱子高度都为-1.

public class LargestRectangle {

    public static void main(String[] args) {
        int height[] = { 2, 1, 5, 6, 2, 3 };
        int ans = getMaxRectangle(height);
        // lift[]=[0,1,1,3,4,3,6] right[]=[0,1,6,4,4,6,6]
        System.out.println("最大的面积位:" + ans);
    }

    /**
     * 遍历每个柱子可以组成的最大面积
     * 
     * @param heights
     * @return 最大的面积
     */
    public static int getMaxRectangle(int heights[]) {
        int ans = 0;
        int n = heights.length;
        int left[] = new int[n + 1];
        int right[] = new int[n + 1];
        processLR(heights, left, right);
        for (int i = 1; i <= n; i++) {
            int tmp = (right[i] - left[i] + 1) * heights[i - 1];
            if (ans < tmp)
                ans = tmp;
        }
        return ans;
    }

    /**
     * 初始化左右两个数组
     * 
     * @param heights
     * @param left
     * @param right
     */
    public static void processLR(int heights[], int left[], int right[]) {
        int n = heights.length;
        // 用临时数组,设置两个哨兵
        int tempArr[] = new int[n + 2];
        tempArr[0] = -1;
        for (int i = 1; i <= n; i++)
            tempArr[i] = heights[i - 1];
        tempArr[tempArr.length - 1] = -1;

        // 用left[i]表示第i个柱子可以最多向左延伸至第left[i]个柱子
        for (int i = 1; i <= n; i++) {
            int k = i;
            while (tempArr[i] <= tempArr[k - 1])
                k = left[k - 1];
            left[i] = k;
        }

        // 用right[i]表示第i个柱子可以最多向右延伸至第right[i]个柱子
        for (int i = n; i > 0; i--) {
            int k = i;
            while (tempArr[i] <= tempArr[k + 1])
                k = right[k + 1];
            right[i] = k;
        }
    }
}

运行的结果:

2.3.1

4.巧妙使用栈

在网上发现另外一个使用一个栈的O(n)解法,代码非常简洁,栈内存储的是高度递增的下标。对于每一个直方图高度,分两种情况。1:当栈空或者当前高度大于栈顶下标所指示的高度时,当前下标入栈。否则,2:当前栈顶出栈,并且用这个下标所指示的高度计算面积。而这个方法为什么只需要一个栈呢?因为当第二种情况时,for循环的循环下标回退,也就让下一次for循环比较当前高度与新的栈顶下标所指示的高度,注意此时的栈顶已经改变由于之前的出栈。

public class largestRectangleArea {

    public static void main(String[] args) {
        int height[] = { 2, 1, 5, 6, 2, 3 };
        int ans = largestRectangleArea(height);
        System.out.println("最大的面积位:" + ans);
    }

    // O(n) using one stack
    public static int largestRectangleArea(int[] height) {
        // Start typing your Java solution below
        // DO NOT write main() function
        int area = 0;
        java.util.Stack<Integer> stack = new java.util.Stack<Integer>();
        for (int i = 0; i < height.length; i++) {
            if (stack.empty() || height[stack.peek()] < height[i]) {
                stack.push(i);
            } else {
                int start = stack.pop();
                int width = stack.empty() ? i : i - stack.peek() - 1;
                area = Math.max(area, height[start] * width);
                i--;
            }
        }
        while (!stack.empty()) {
            int start = stack.pop();
            int width = stack.empty() ? height.length : height.length
                    - stack.peek() - 1;
            area = Math.max(area, height[start] * width);
        }
        return area;
    }
}

这是看到别人的推演过程,之前看到,就添加到笔记了,没有原著的地址,所以没法标明出处:

一个思维历程

那么这个算法真的就是我等凡夫俗子不能想出来的?难道我们只能仰望高山,恨自己智商不高?我还真不服气呢,于是又静下心去思考这个问题。

这次我们不从已知条件推结果,而直接从结论入手,就是说假设现在已经找到了面积最大的那个矩形。接着我们来分析该矩形有什么特征,然后可以用下面两种方法之一来缩减问题的规模(因为这两种方法都不用找出所有的矩形一一比较)。

找出满足这些特征的矩形,面积最大的矩形肯定是其中之一;
排除那些不满足这些特征的矩形,面积最大的矩形在剩下的那些矩形里面。
为了使考虑情况尽可能全面,画了许多直方图,防止使用原题目图片可能存在的一些特定假设,其中一个直方图如下图:

2.4.1

题目情况分析

通过不断地对多个直方图的观察,发现面积最大的那个矩形好像都包含至少一个完整的bar,那么这条规律适用于所有的直方图吗?我们用反证法来证明,假设某个最大矩形中每个竖直块都是所在的bar的一小段,那么这个矩形高度增加1后仍然是一个合法的矩形,但新的矩形面积更大,与假设矛盾,所以面积最大的矩形必须至少有一个竖直块是整个bar。

至此我们找到了面积最大矩形的一个特性:各组成竖直块中至少有一个是完整的Bar。有了这条特性,我们再找面积最大的矩形时,就有了一个比较小的范围。具体来说就是针对每个bar,我们找出包含这个bar的面积最大的矩形,然后只需要比较这N个矩形即可(N为bar的个数)。

那么问题又来了,如何找出“包含某个bar的面积最大的矩形呢”?对于上面的直方图,包含下标为4的bar的最大矩形如下图橘黄色部分:

2.4.2

局部最大矩形

简单观察一下,就会发现要找到包含某个bar的最大矩形其实很简答,只需要找到高度小于该bar的左、右边界即可,上图中分别是下标为1的bar和下标为10的bar。

至此问题已经变为“对于给定的bar,如何确定高度比它小的左、右边界”。其实求左边界和右边界是同样的求法,下面我们考虑求每个bar的左边界。最直接的思路是对于每个bar,扫面其前面所有的bar,找出最后一个高度小于它的bar,这样的话时间复杂度明显又是N^2 ,Holy Shit。

到这里似乎没有路可走了,但如果我们继续绞尽脑汁地去想,可能(或许你对栈理解的很深入,或许是你在一个类似的问题中用到了栈,当然你也可能想到动态规划的思想,那也是可行的)会联想到栈这一数据结构。用栈维护一个高度递增的bar的集合,也就是说栈底到栈顶部对应的bar的高度越来越大。那么对应一个刚读入的bar,我们只需要比较它的高度和栈顶对应bar的高度,如果当前bar比较高,则弹出栈顶元素继续比较,直到栈顶bar比它低或者栈为空。之后,将当前bar入栈,更新栈内的递增序列。

我们从左到右扫一遍得到每个bar对应的左边界,然后从右到左扫一遍得到bar的右边界。两次扫描过程中,每个bar都只有出栈、入栈操作,所以时间复杂度为O(N)。通过这样的预处理,即可以O(N)的时间复杂度得到每个bar的左右边界。之后对于每个bar求出包含它的最大面积,也即是由左右边界和bar的高度围起来的矩形的面积。再做N次比较,即可得出最终的结果。

这里先预处理用两个栈扫描两次得到左、右边界,再计算面积,是按照推导过程一步一步来的。当我们写完程序后,再综合看这个问题,可能会发现其实没必要这样分开来做,我们可以在扫描的同时,维护一个递增的栈,同时在“合适的”时候计算面积,然后更新最大面积。具体实现方法就是前面给出的那个神奇的算法,不过现在看来一点也不神奇了,我们已经探索到了它背后的思维历程。

当然,条条道路通罗马,上面思维过程只是其中一条通往解决方案的路径,你可能以另一种思维过程找到了答案。不过,我们上面的整个推导过程没有涉及一些类似“神谕”的启发,只是一些简单的方法:比如从结论推导、反证法、归纳总结、联想(可能联想到栈有点难)等,因此每个人都可以学会,并且很容易被大脑记住。值得注意的是,我们的整个思考过程并不简简单单地跟上面写的那样是线性的,它更可能是树形的,只是我们剪去了那些后来证明行不通的枝。

Demo:http://download.youkuaiyun.com/detail/two_water/9670562


三、思考

最后奉上看到别人写的东西,略有感想,故分享。

3.1.1

大数据领域数据架构的工业互联网数据架构设计 工业互联网作为第四次工业革命的重要驱动力,正在深刻改变传统制造业的生产方式和商业模式。本文旨在探讨工业互联网环境下的大数据架构设计,重点解决工业数据采集、传输、存储、处理和分析等关键环节的技术挑战。工业互联网数据架构的核心组件大数据技术在工业场景下的应用数据治理和质量控制边缘计算与云计算的协同架构背景介绍:建立基本概念和问题域核心架构:详细解析工业互联网数据架构技术实现:通过代码和数学模型展示关键技术实践案例:展示真实场景应用工具资源:推荐实用开发工具和学习资源。 阅读详情

相关推荐

【高低温试验】试验报告模板

高低温循环试验,验证被测设备(DUT)在极端高温、低温环境下的性能稳定性、功能可靠性及安全性,确保其符合设计规范和相关标准(如GB/T 2423.1、GB/T 2423.2)。:验证设备在剧烈温度变化下的耐受能力(如-40℃↔+85℃,温变速率≥10℃/min)。低温测试标准:GB/T 2423.2-2008(温度-40℃,保持时间4小时):模拟高温高湿环境(如温度+60℃,湿度95%RH),测试防潮性能。

电路巫师把一切不可能变成不可能 1565

直方图之回顾

频数直方图:高度代表频数密度(频数/组距),此时组距为1,则面积代表频数频率直方图:高度代表频率密度(频率/组距),面积代表频率!!

m0_51984816的博客 3366

Python爬虫教程:抓取短视频平台数据(以抖音和快手为例)

为什么抓取短视频平台数据?内容分析:通过抓取短视频平台上的视频内容、标题、标签等数据,可以进行内容分类、趋势分析、话题分析等。情感分析:抓取视频的评论数据,并进行情感分析,帮助企业或组织了解公众的情绪反馈。用户行为分析市场监测:通过抓取特定关键词或标签下的视频数据,分析市场趋势,进行竞争对手分析。短视频平台数据类型:视频信息:包括视频标题、描述、标签、作者等。用户信息:包括用户的昵称、粉丝数、关注数等。互动数据评论数据:视频下的用户评论内容及用户信息。

2201_76125261的博客 3662

直方图 (Histogram)

用矩形的面积来表示频数分布的图形 在直角坐标中,用横轴表示数据分组,纵轴表示频数密度,各组与相应的频数就形成了一个矩形,即直方图 直方图下的总面积等于总频数(或1) 适用于定距变量 ...

6285

智能驾驶辅助系统(ADAS)全解析:功能详解 + 技术原理 + 实战案例

智能驾驶辅助系统(ADAS)是现代汽车技术的重要组成部分,旨在提升驾驶安全性和便利性。本文详细解析了ADAS的多个功能模块,包括自适应巡航控制(ACC)、车道偏离预警/车道保持辅助(LDW/LKA)、前向碰撞预警/自动紧急制动(FCW/AEB)、盲区检测/变道辅助(BSD/BSM)、倒车影像、自动泊车辅助(APA)、交通标志识别(TSR)、自动远光控制(AHB)、后方交叉来车预警(RCTA)和驾驶员疲劳监测。每个功能模块都基于特定的技术原理,如毫米波雷达、摄像头、传感器融合和深度学习算法,以实现对车辆周围环

weixin_43199439的博客 2102

【MATLAB例程】三维下的IMM(交互式多模型),模型使用CV(匀速)和CA(匀加速),滤波使用EKF。附完整代码

CV模型:状态包含位置、速度和零加速度(9维状态),状态转移矩阵忽略加速度项CA模型:完整包含位置、速度和加速度(9维状态),状态转移矩阵包含二次项过程噪声矩阵Q分别根据两种模型的运动特性推导。

985工科博士毕业,专攻定位、导航和滤波等算法研究。从业10年,主要使用MATLAB 561

leetcode_question_85 Largest Rectangle in Histogram

Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram. Above is a histogram where width

ZkvIA的博客 1万+

4位无符号比较器设计

4位无符号比较器设计

好好学习,天天向上 7891

描述性统计分析 | 直方图

直方图的详细讲解

weixin_42444823的博客 2774

鸢尾花分类预测

鸢尾花数据总用有150个样本,是一个典型的分类数据集,共有3个类别,分别是山鸢尾(Iris-setosa)、变色鸢尾(Iris-versicolor)和维吉尼亚鸢尾(Iris-virginica),每个样本的特征有4列sepal_length:萼片长度sepal_width:萼片宽度petal_length:花瓣长度petal_width:花瓣宽度这里我们定义了随机森林模型作为实例,来进行模型训练,之后我们会对其使用网格搜索找到最优的参数。

优快云 精品推荐 2188

ccSwitch 安装使用指南,claude code的最佳搭档

ccSwitch 是一款真正为 AI 编程开发者打造的效率工具。它把原本繁琐的配置管理工作,简化成了直观的图形界面操作。无论你是需要在多个 API 提供商之间切换,还是想要统一管理多款 AI 编程工具,ccSwitch 都能帮你大幅提升效率。如果你是重度 AI 编程工具用户,强烈推荐尝试一下 ccSwitch,相信它会成为你开发工具箱中不可或缺的一员。项目地址。

篮球界最会写bug的人;程序猿中打球最菜的人。 1287

LeetCode:Largest Rectangle in Histogram(直方图中最大矩形面积)

84. Largest Rectangle in Histogram Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.   Ab...

但行好事,莫问前程 957

【实战篇导读】四足机器人运动控制导读

认知有限,望大家多多包涵,有什么问题也希望能够与大家多交流,共同成长!本文先对四足机器人运动运动控制系统及相关算法做个简单的介绍,具体内容后续再更,其他模块可以参考去我其他文章主要介绍了波士顿spot机器人的发展历史、四足机器人的硬件系统及电机执行器组成包括硬件系统、关节电机执行器,机载传感器机处理器及电气连接等。概述了四足机器人规划控制、感知、定位及局部地图的相关算法方向。

qq_35635374的博客 678

[LeetCode]—Largest Rectangle in Histogram 求直方图最大填充矩形面积

Largest Rectangle in Histogram

清水 977

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

LeetCode(084)-Largest Rectangle in Histogram(直方图最大矩形面积)

题目: Given n non-negative integers representing the histogram’s bar height where the width of each bar is 1, find the area of largest rectangle in the histogram. Above is a histogram where width of ea...

Fly_Fly_Zhang的博客 691

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

LeetCode 84. Largest Rectangle in Histogram(直方图中最大矩形面积)

题目描述:    Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.        Above is a histogram where ...

andersonxie的博客 2800

深度学习工具包 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")

Largest Rectangle in Histogram (直方图中最大面积) 【leetcode】

题目: Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram. Above is a histogram wh

Havenoidea 的专栏 7296

LeetCode | Largest Rectangle in Histogram(直方图围城的最大矩形面积)

Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram. Above is a histogram where width o

solar一抹阳光的专栏 1137

【LeetCode】84. Largest Rectangle in Histogram——直方图最大面积

Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram. Above is a histogram where width of each b...

weixin_33973600的博客 82

4.1.3LeetCode: Largest Rectangle in Histogram(直方图最大面积)

http://www.cnblogs.com/avril/archive/2013/08/24/3278873.html 具体的题目描述为:   Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the are

ZhikangFu的专栏 690

【leetcode每日刷题】Largest Rectangle in Histogram

https://leetcode.com/problems/largest-rectangle-in-histogram/ 求直方图中的最大矩形 从左到右找到最高的矩形,然后从右向左计算最大的面积。 class Solution(object): def largestRectangleArea(self, heights): """ :type h...

菜菜鸟的博客 173

leetcode栈--2、largest-rectangle-in-histogram(直方图最大面积)

题目描述 Givennnon-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram. Above is a histogram where wi...

weixin_30820077的博客 115

最大矩形(Stack,Vector,Queue,Deque)

Largest Rectangle in Histogram:https://leetcode.com/problems/largest-rectangle-in-histogram/description/public int largestRectangleArea(int[] height) { int len = height.length; Stack&l...

heiheibupt的博客 215

Leetcode -- Maximal Rectangle

https://oj.leetcode.com/problems/maximal-rectangle/ Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area  public int maximalRectan

chaochen1407的专栏 387

算法设计与分析第一周练习

题目 Given n non-negative integers a1, a2, …, an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find t...

Vilin的博客 281

Leetcode. Largest Rectangle in Histogram

1. 题解 题目 链接🔗:84. Largest Rectangle in Histogram 这道题和42. Trapping Rain Water有些相像,但是42题求的是能围住的最大面积,而本题求的是连成的矩阵的最大面积,因而在计算面积的方法上有些许不同。85. Maximal Rectangle就是在本题基础上的变式,通过一系列变化可以使用本题方法。 分析 简单分析可以知道最大矩形面积有两种情况: 当前矩形的高度heights[i] * 1 当前矩形的高度heights[i] * (向右第一个比

三明治文鱼的博客 7797
上一篇: 微信小程序学习(6)_配置详解
下一篇: Android 网络框架_常用的网络框架
Two_Water
博客等级 码龄12年 573粉丝 134原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值