数组中的逆序对

【剑指offer】数组中的逆序对 思路:最简单的方法是顺序数组,将每个数字与后面的比较,统计逆序对的个数,这种方法的时间复杂度为O(n*n),这种方法写出的代码在九度OJ上测试,会超时。剑指offer给出了归并排序的思路,这个有点难想到啊,也可能是我太弱了,根本没往这方面想!理解了思路,就不难了,将数组划分成两个子数组,再将子数组分别划分成两个子数组,统计每个子数组内的逆序对个数,并将其归并排序,再统计两个子数组之间的逆序对个数,并进行归并排序。这就是归并排序的变种,在归并排序代码的基础上稍作改进即可。 合理还要注意一点:全局变量c 阅读详情
题目:
在数组中的两个数字如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。

分析:
一、首先,最直观的算法就是我们遍历数组中的每个数字,在遍历到一个数字时,把这个数字和之后的数字作比较得出结果,这种算法的时间复杂度为O(n2).
二、要求出逆序对的个数,我们可以换一种思路,如果我们将数组按照从小到大的顺序排序,那么这个数组的逆序对就为0,假设我们的排序算法每次只能交换数组中相邻的数字,那么排序过程中交换的次数就是逆序对的个数。但是有一个问题,我们给排序算法加上这样一个限制之后,排序算法的时间复杂度也不达不到我们所期望的O(nlogn),不过我们可以考虑对归并排序进行一些改造,基于归并排序实现我们要的结果。

基于归并排序的实现方法,时间复杂度为O(nlogn):

class Solution 
{
public:
    int InversePairs( vector<int> data )
    {
        if ( data.empty() )
            return 0;

        vector<int> copy( data );
        int count = InversePairsCore( data, copy, 0, copy.size()-1 );
        return count;
    }

    int InversePairsCore( vector<int>& data, vector<int>& copy, int start, int end )
    {
        if ( start == end )
        {
            copy[start] = data[start];
            return 0;
        }

        int length = ( end - start ) / 2;
        int left = InversePairsCore( copy, data, start, start+length );
        int right = InversePairsCore( copy, data, start+length+1, end );

        int i = start + length;
        int j = end;
        int indexCopy = end;
        int count = 0;

        while ( i >= start && j >= start+length+1 )
        {
            if ( data[i] > data[j] )
            {
                copy[indexCopy--] = data[i--];
                count += j-start-length;
            }
            else
            {
                copy[indexCopy--] = data[j--];
            }
        }

        for ( ; i >= start; --i )
            copy[indexCopy--] = data[i];
        for ( ; j >= start+length+1; --j )
            copy[indexCopy--] = data[j];

        return left+right+count;
    }

};

int main( void )
{
    Solution sos;
    vector<int> data = { 7, 5, 6, 4 };
    cout << sos.InversePairs( data ) << endl;
    return 0;
}
图像特征(一)——颜色特征(颜色直方图,颜色矩,颜色集,颜色聚合向量和颜色相关图) 本文主要是为了更好地理解图像特征,理解各方法的原理。转载请注明出处https://mp.youkuaiyun.com/console/editor/html/105090183 图像模式识别的一般步骤为:输入图像--图像预处理--特征提取--特征选择--图像分类--输出结果。 图像特征主要有:颜色特征、形状特征、纹理特征和空间关系特征。 本文主要介绍颜色特征,并给出matlab上实现的demo。 颜... 阅读详情

相关推荐

【人工智能】AI算法系统设计与算法建模的详细阐述

AI算法系统设计与算法建模是人工智能领域中的核心任务之一,它涉及从问题定义、数据收集、算法选择、模型构建到系统部署的全过程。以下是对AI算法系统设计与算法建模的详细阐述

weixin_51306394的博客 4355

C++实现逆序对

逆序对和数组小和都是归并排序的引申,所以放到一起了。 1. 问题描述 设 A[1…n] 是一个数组,如果对于 i < j 有 A[i] > A[j], 则 A[i] 和 A[j] 构成一对逆序。给定一个数组,计算数组中逆序对的个数。例如数组 a[] = {1, 4, 3, 2}, 则 {4, 3} {4, 2} {3, 2}是逆序对,返回 3。 2. 解决 这里主要是应用了归...

暮日落流年的博客 3511

ArcGIS实战:手把手教你用DEM和灾害点数据,5步搞定地质灾害风险区划图

本文详细介绍了使用ArcGIS进行地质灾害风险评估的完整流程,从DEM和灾害点数据出发,通过五步标准化操作生成专业风险区划图。重点讲解了信息量模型的应用,帮助读者掌握GIS技术在地质灾害易发性评价中的实践方法,提升风险评估效率与准确性。

weixin_30696427的博客 426

关于逆序对的两种做法(归并排序+树状数组c++)

这些天来测试的时候遇到了几次逆序对的题目,但没有太在意,已经跪了好几次了,所以今天打算学习总结一下逆序对的两种做法。 首先是归并排序 归并排序的模板 #include using namespace std; int a[100000],temp[100000]; void merge_i(int l,int mid,int r) { int i=l,j=mid+1,k=l

qq_32624861的博客 575

linux下autocad完美替代品bricscad的安装运行

前言 在Linux平台下,能完美兼容.dwg文件的软件并不多。 虽然国产的中望和浩辰为适配uos操作系统,近期都推出了linux版本,但目前好像还没有对应的破姐流出。(如果有的话请私信我或留下评论) 然而有了这一款源自比利时的软件——bricscad,linux下查看和编辑.dwg文件再也不是噩梦了! 安装pj 资源链接:https://pan.baidu.com/s/1dC7zarlqwuO5fa4CBL_KGQ 提取码:24j6 1.下载对应的压缩包,解压并安装其中对应的deb或rpm软件包。 2.在C

weixin_35259117的博客 4487

ChromeOS安装教程

ChromeOS,是基于Linux内核研发的ChromiumOS开源系统的闭源系统,最大的特色就是内置了Chrome浏览器,早期主要以Web云端应用程序为主,后来逐渐引入了Android子系统和Linux子系统。本文主要简述摸索的家用笔记本安装ChromeOS安装方法,供各位玩机朋友参考。

weixin_45751495的博客 8122

洛谷4223 BZOJ5058 期望逆序对 期望 组合数学 矩阵乘法 树状数组

题目链接 题意: 给你一个长度为nnn的排列,有kkk次操作,每次随机两个不同的位置,交换两个位置的元素,求kkk次交换后期望的逆序对数。为了避免答案是小数的问题,结果乘上(Cn2)k(C_{n}^{2})^k(Cn2​)k,并且对1e9+71e9+71e9+7取模。n&amp;lt;=500000,k&amp;lt;=1e9n&amp;lt;=500000,k&amp;lt;=1e9n&lt;=...

forever_shi的博客 1394

NMOS管和PMOS管做开关控制电路

NMOS管和PMOS管做开关控制电路

while(1) 3万+

2024年第十五届蓝桥杯C/C++大学B组题 B逆序对期望

以2 3 4和1 5 6的比较为例,1<2,因为2 3 4子序列在之前的排序中已经有序,则之后的数3 4都比2大,所以也理所当然地比1大,因此从逆序数对开始出现的两个位置相减就能获得逆序对的数量。在这里,逆序对的个数期望是由每一个可能出现的结果除以操作总数再相加,原因是每一次交换的可能性都是一样的(均匀随机),则只需要考虑其相对于操作总数所占的比,数学期望。虽然本道题是博主没见过的题型,但对其深入的了解和反复推敲是非常值得的,这样不仅能复习巩固旧的知识,还能去了解新的内容,对个人的能力提升是个非常不错的。

Y_P_L_D的博客 2189

get_seed协议

【代码】get_seed协议。

a545958498的博客 914

11、系统稳定性分析与李雅普诺夫函数的应用

本文深入探讨了李雅普诺夫函数在系统稳定性分析中的核心作用,重点介绍了时变与时不变系统的稳定性判据差异,以及巴尔巴拉特引理在处理非自治系统中的应用。文章还阐述了正线性系统与严格正实传递函数的性质及其在非线性控制系统中的重要性,并展示了李雅普诺夫函数在评估主导时间常数和设计快速干扰抑制控制策略方面的实际应用。通过具体示例和流程图,系统地总结了李雅普诺夫方法在稳定性分析、性能评估与控制器设计中的多维度价值,同时指出了当前挑战与未来发展方向。

Jerry的专栏 93

逆序对与期望

对于一个长度固定的区间,可以分区间内和区间内外分别考虑。对于后者,无论区间内怎么重排,都可以直接计算出与区间外的逆序对数,像滑动窗口一样直接处理即可。对于后者,用树状数组维护逆序对。但需要注意循环枚举应该从后往前,从而保证每次查询时在其之后的数的相对大小已存入树状数组中。每次可以选择任意长度的连续区间进行重排,求期望的逆序对个数。的排列中有一些数是不确定的,求该排列的逆序对。对于每一对数,是否成为逆序对的概率显然为。的连续区间进行重排,求期望的逆序对个数。以下均设当前的序列逆序对的数量为。

scy923的博客 1051

Sentaurus TCAD建模:宽温区n型FinFET模型校准与低温仿真分析

本文基于Sentaurus TCAD平台,建立了n型FinFET的宽温区(233K-393K)仿真模型,解决了低温(73K-193K)仿真失效问题。研究对比了Sprocess工艺仿真与SDE几何建模两种方法,分析了载流子冻析效应、不完全电离和迁移率退化等低温物理机制。通过优化模型参数,实现了在233K、313K和393K条件下仿真误差小于10%,并建立了符合物理趋势的低温外推模型。研究提供了完整的Sentaurus TCAD代码实现,包括器件结构定义、物理模型配置和温度相关参数校准,为宽温区FinFET仿真

huanghm88的专栏 265

【数组】 数组中的逆序对

题目描述 在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007 输入描述: 题目保证输入的数组中没有的相同的数字 数据范围: 对于%50的数据,size<=10^4 对于%75的数据,size<=10^5 对于%100的数据...

永生只是一场幻梦 2721

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

python 数组中的逆序对

''' 在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007 输入描述: 题目保证输入的数组中没有的相同的数字 数据范围: 对于%50的数据,size<=10^4 对于%75的数据,size<=10^5 对于%100的数...

WYXHAHAHA123的博客 1769

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

数组之数组中的逆序对

1.本题知识点    归并排序 2. 题目描述   在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P%1000000007 3. 思路    ① 归并排序,不会的请跳到我的基础算法博客查看。    ② 归并过程中,排序的同时记录逆序对的个数。    Java版本:...

守得云开见月明 367

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

【分治】数组中的逆序对

本文介绍了两种基于归并排序的解法来计算数组中的逆序对数量。第一种思路利用升序排序,在合并过程中统计左区间大于右区间的元素个数;第二种思路通过降序排序,统计右区间小于左区间的元素个数。两种方法均通过分治策略将时间复杂度优化至O(nlogn),避免了暴力解法的O(n²)复杂度。代码实现中展示了升序合并时的关键判断逻辑,通过临时数组辅助完成排序与统计。该问题展示了归并排序在统计特定顺序对时的巧妙应用。

lirendada的博客 1380
上一篇: 第一个只出现一次的字符
下一篇: 两个链表的第一个公共结点
Findway_
博客等级 码龄10年 36粉丝 117原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值