[Leetcode] 164. Maximum Gap 解题报告

实现高精度卷积混响--MATLAB仿真篇 一、前言 之前在STM32F407上现实了直播声卡,实现的经典Schroeder混响模型和Moorer混响模型,得到不错效果。后来得知卷积混响最为真实地表现空间的特性,所以也就尝试在MCU上实现一个高精度的卷积混响(卷积点数为32768),目前MCU出来的混响效果算得上一流水准,本人也在计划在ADI的21489或者SC584上更高精度的卷积混响。 二、卷积方式 1、conv1是使用MATLAB自带卷积函数conv 2、conv2和conv3是改进后卷积过程,具有减少运算量特点,方便嵌入式移植 clear; 阅读详情

题目:

Given an unsorted array, find the maximum difference between the successive elements in its sorted form.

Try to solve it in linear time/space.

Return 0 if the array contains less than 2 elements.

You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.

思路:

1、桶排序:设数组中有n个元素,其中最大值为Max,最小值为Min,则排序后相邻两个元素的差值的最大值不会小于ceil((Max - Min)/(n - 1))(可以利用反证法进行证明)。因此我们的做法是:设置桶的大小为size = ceil((Max - Min)/(n - 1)),那么桶的个数为(Max - Min) / size + 1;我们遍历数组,对每个桶计算其最大值和最小值,最后遍历一遍桶,因为最大的gap不会出现在桶内部,而在桶之间,所以获得“后一个非空桶的最小值减前一个非空桶的最大值的最大值”,即为我们的题目所求。该思路的时间复杂度和空间复杂度都是O(n)。

2、基数排序:这道题目还可以使用基数排序来完成。我们先简单介绍一下基数排序的概念:就是按照数字的低位到高位依次对每一位进行排序,比如5632, 7689, 2136, 2137, 2148, 6782。先对最后一位进行排序,可以装入十个桶内,对应的桶内装的数字在该位对应的是0~9这十个数字,然后接着对倒数第二位再进行排序,依次往前,直到排到最高位。为了便于理解,我们把每次排序之后的结果列举如下:

倒数第一位:5632, 6782, 2136, 2137, 2148, 7689;

倒数第二位:5632, 2136, 2137, 2148, 6782, 7689;

倒数第三位:2136, 2137, 2148, 5632, 7689, 6782;

倒数第四位:2136, 2137, 2148, 5632, 6782, 7689。

在进行基数排序之后,我们就可以通过一次线性扫描从而得到Maximum Gap。基数排序的时间复杂度是O(k*n),空间复杂度是O(k + n)。由于题目中限定输入数据在32位有符号整数的范围之内,所以可以认为k是一个小于等于32位的常数,所以用基数排序也符合本题目的要求。

代码:

1、桶排序:

class Solution {
public:
    int maximumGap(vector<int>& nums) {
        if(nums.size() < 2) {
            return 0;
        }
        int Max = *max_element(nums.begin(), nums.end());
        int Min = *min_element(nums.begin(), nums.end());
        if(Max == Min) {
            return 0;
        }
        int gap = ceil(static_cast<double>(Max - Min) / (nums.size() - 1));
        int bucketNum = ceil(static_cast<double>(Max - Min) / gap);
        vector<int> bucketsMin(bucketNum, INT_MAX);
        vector<int> bucketsMax(bucketNum, INT_MIN);
        for(int i = 0; i < nums.size(); ++i) {
            if(nums[i] == Max || nums[i] == Min) {
                continue;
            }
            int idx = (nums[i] - Min) / gap;
            bucketsMin[idx] = min(bucketsMin[idx], nums[i]);
            bucketsMax[idx] = max(bucketsMax[idx], nums[i]);
        }
        int ans = INT_MIN;
        int previous = Min;
        for(int i = 0; i < bucketNum; ++i) {
            if(bucketsMin[i] == INT_MAX || bucketsMax[i] == INT_MIN) {
                continue;
            }
            ans = max(ans, bucketsMin[i] - previous);
            previous = bucketsMax[i];
        }
        ans = max(ans, Max - previous);
        return ans;
    }
};

2、基数排序:

class Solution {
public:
    int maximumGap(vector<int>& nums) {
        if (nums.size() < 2) {
            return 0;
        }
        int length = to_string(*max_element(nums.begin(), nums.end())).size();
        int radix = 1, max_gap = 0, size = nums.size();
        for (int i = 0; i < length; ++i) {          // step 1: radix sort
            vector<int> buckets(10, 0), temp_nums(size);
            for (int val : nums) {                  // store the appearance count to buckets
                ++buckets[(val / radix) % 10];
            }
            for (int j = 1; j < 10; ++j) {          // make buckets[j] the index of nums[j] in temp_nums
                buckets[j] += buckets[j - 1];
            }
            for (int j = size - 1; j >= 0; --j) {   // store the data to temperary array
                temp_nums[--buckets[(nums[j] / radix) % 10]] = nums[j]; 
            }
            for (int j = 0; j < size; ++j) {        // assign the sorted data to the nums
                nums[j] = temp_nums[j];
            }
            radix *= 10;
        }
        for (int i = 1; i < size; ++i) {            // step 2: get max gap
            max_gap = max(max_gap, nums[i] - nums[i - 1]);
        }
        return max_gap;
    }
};
Mac安装Claude Code的3种方式及5类报错解决方案 介绍在Mac上安装Claude Code的3种实测可行方式(官方dmg、Homebrew+ARM原生构建、Docker容器化),并针对Gatekeeper签名验证失败、Rosetta 2内存对齐崩溃、Python ABI兼容性冲突等5类高频报错提供根因分析与可复现解决方案,覆盖M1–M3及Intel 阅读详情

相关推荐

安装IC Complier 2(安装synposys的其他工具也可以来看看,因为殊途同归)

安装ICC2

hjt66666的博客 5816

[leetcode] 164. Maximum Gap 解题报告

题目链接:https://leetcode.com/problems/maximum-gap/ Given an unsorted array, find the maximum difference between the successive elements in its sorted form. Try to solve it in linear time/space.

小榕流光的专栏 1441

niushop靶场漏洞查找-文件上传漏洞等(超详细)

发现报错,而且这个报错十分熟悉,与我们所学的sqli报错注入特别像。这里查询到后面的url有且仅有一个,目测估计是后台。上传的图片是包含一句话木马的图片。发现获取到了webshell。实战漏洞-niushop。

qq_59020256的博客 1732

hdu1067 N - Gap

Home Problems Status Contest [ak1] Logout WUST ACM CLUB SUMMER TRAINING (3) 277:06:36 307:00:00 Overview Problem Status Rank A B C D E F G H I J K L M N O

习惯与规则决定命运 1976

基于ASP.NET+SQLServer的美妆网站的设计与实现

通过本次ASP.NET MVC美妆商城项目的开发,我们实现了一个功能完善、性能稳定的在线购物平台。该项目不仅提升了用户的购物体验,也为商家提供了一个高效的商品管理和销售渠道。未来,我们将持续优化系统功能,提升用户体验,以适应不断变化的市场需求。

毕业设计大牛哥 1517

基于EKF的UWB-IMU融合定位系统在农业机器人中的抗干扰优化与Matlab仿真

本文探讨了基于扩展卡尔曼滤波(EKF)的UWB-IMU传感器融合定位系统在农业机器人中的应用。通过Matlab仿真验证,该系统有效解决了农业环境中UWB信号遮挡和IMU累积误差问题,实现了厘米级高精度定位,显著提升了机器人在复杂场景下的抗干扰能力和导航可靠性。

numpy6sculptor的博客 629

手工消除dataguard的gap

1.在备库查询有哪些日志丢失,没应用到备库  SQL> select * from V$ARCHIVE_GAP;    THREAD# LOW_SEQUENCE# HIGH_SEQUENCE# ---------- ------------- --------------          1          9873        9876 我们可以看到9873到9876这四个归档日

迎寒的专栏 738

病理组学分析系列教程1:使用Python-histolab进行病理图像预处理,tiles切片自动生成

病理图像tiles自动生成,WSI图像预处理

qq_43449643的博客 1749

164. Maximum Gap

Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see thek numbers in the window. Each time the sliding window

u010005161的博客 966

Python控制TEMI1000/TEMI1500测试温箱

该温箱是我司从昆山振弘检测设备有限公司采购的TEMI 1000,但是控制器用的是韩国的,关于控温箱这个项目,可参考的资料仅有一份官方的manual,里面包含一些命令格式。只要你有温箱,就应该可以向厂家索取该文档。该温箱的通讯接口只有一个RS232接口,要想实现远程控制,需要有串口转USB的线;类似于下图所以,想依靠python来与之进行通信,还是要通过python 的pyserial库,关于怎么安装pyserial,过于简单,这里不做赘述,可自行百度。

xgh1951的博客 1万+

【网络安全】SSRF漏洞讲解

SSRF漏洞讲解一、初识SSRF漏洞1.定义2.产生原理3.会导致的危害4.常见产生SSRF的地方5.常见缺失函数二、SSRF漏洞利用1.函数(1) file_get_contents(2)fsockopen()(3) curl_exec()2.协议(1)file协议(2)http协议(3)dict协议(4)gopher协议三、绕过1.绕过方式(1)检查IP是否为内网IP(2)Host获取与DNS绕过(3)通过各种协议(4)利用URL解析器滥用问题四、修复修复方案五、小结 一、初识SSRF漏洞 1.定义

你在看屏幕的同时,屏幕也在注视着你 3189

[leetcode] 164. Maximum Gap

题目链接:https://leetcode.com/problems/maximum-gap/ 题意:给定一个无序数组,求有序情况下相邻元素差最大为多少? 要求:时间复杂度和空间复杂度均为O(n)法一:我们很容易能够想到基数排序,它的时间复杂度和空间复杂度都是O(n),排好序之后扫一遍就行了。这样当然是没有问题的。代码如下:class Solution { public: void rad

曲径通幽处 1091

【软件测试】人工智能(AI)在软件测试领域的应用

AI在软件测试领域的应用使测试过程更加自动化、高效和智能。它可以帮助测试团队减轻负担,更快地识别和修复问题,最终提高软件的质量和可靠性。随着AI技术的不断进步,未来AI在软件测试领域的应用将更加广泛和深入。

weixin_46453070的博客 4407

【LeetCode解题报告】164. Maximum Gap

题目来源:https://leetcode.com/problems/maximum-gap/description/题目:Given an unsorted array, find the maximum difference between the successive elements in its sorted form.Return 0 if the array contains les...

Angry_Bird16的博客 335

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

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

【LeetCode】164.Maximum Gap(Hard)解题报告

【LeetCode】164.Maximum Gap(Hard)解题报告题目地址:https://leetcode.com/problems/maximum-gap/description/ 题目描述:   Given an unsorted array, find the maximum difference between the successive elements in its sor

郝春雨的博客 465

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

LeetCode(164) Maximum Gap

题目如下: Given an unsorted array, find the maximum difference between the successive elements in its sorted form. Try to solve it in linear time/space. Return 0 if the array contains less than 2 eleme

BUILD 4811

全球国家地区城市数据

MySQL全球国家地区城市数据报。。。。。。。。。。。。

Maximum Gap Leetcode #164 题解[Python]

题目来源 https://leetcode.com/problems/maximum-gap/description/ 题意分析 Given an unsorted array, find the maximum difference between the successive elements in its sorted form. Return 0 if the array ...

Wayne_Mai的博客 1053

[LeetCode]164. Maximum Gap

原题链接:https://leetcode.com/problems/maximum-gap/ 这道题如果是O(nlgn)方法肯定很简单,排序后找最大gap就行了。但如果要求O(n)时间完成的话,难度就大大加大了。所以我们用桶排序的方法来做这道题。 有关桶排序的简介,大家可以参考维基-桶排序。我们来介绍一下桶排序的应用,桶排序就是将一定范围的值全部丢到同一个桶里。所以我们只要合理安排桶的个数,让

foolman 779

leetcode-164 Maximum Gap

1.leetcode链接(hard) 2. 题目描述 给定未排序的数组,找到其排序形式中的连续元素之间的最大差异。 如果数组包含少于2个元素,则返回0。 Case example: Input: [3,6,9,1] Output: 3 Explanation: 排序后是[1,3,6,9], (3,6)或(6,9) 有最大差3. 3.思路分析 复杂度分析 ...

公众号/知乎: AI算法札记,欢迎关注交流 338

LeetCode 164. Maximum Gap

LeetCode 164. Maximum Gap 问题来源LeetCode 164. Maximum Gap 问题描述 Given an unsorted array, find the maximum difference between the successive elements in its sorted form. Try to solve it in linear

yanqinghe123的专栏 501

LeetCode //C - 164. Maximum Gap

【代码】LeetCode //C - 164. Maximum Gap。

Made in Code 1126

Leetcode 164 Maximum Gap 桶排序好题

Given an unsorted array, find the maximum difference between the successive elements in its sorted form. Try to solve it in linear time/space. Return 0 if the array contains less than 2 elements

无名山丘,崛起成峰 4243

[LeetCode164] Maximum Gap

Given an unsorted array, find the maximum difference between the successive elements in its sorted form. Try to solve it in linear time/space. Return 0 if the array contains less than 2 elements

coder 进阶的专栏 1414

Leetcode164 Maximum Gap

leetcode164题

YinRJ的博客 137

Leetcode 164. Maximum Gap

这道题先排序再遍历一遍能够直接AC,但是在讨论区有人提出了使用桶排序的方式,理论上比直接调库排序更加快,但实际上直接调库速度更快。 首先,定义max, min, N分别为数组最大值、最小值、以及数组长度,根据抽屉原理,显然maximum gap ≥ gap = round_up[(max - min) / (N-1)]。反证法如果maximum gap < gap,则会出现 min +...

I_ren的博客 196

【LeetCode】164. Maximum Gap 最大间距(Hard)(JAVA)

【LeetCode】164. Maximum Gap 最大间距(Hard)(JAVA) 题目地址: https://leetcode.com/problems/maximum-gap/ 题目描述: Given an unsorted array, find the maximum difference between the successive elements in its sorted form. Return 0 if the array contains less than 2 elements.

qq_16927853的博客 194
上一篇: [Leetcode] 163. Missing Ranges 解题报告
下一篇: [Leetcode] 165. Compare Version Numbers 解题报告
魔豆Magicbean
博客等级 码龄19年 146粉丝 742原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值