数据结构面试题总结1——数组:求最大、次大值

求数组中的最大值和次大值 1. 问题 数组中的最大值和次大值 输入:A[1…n]=<a1, a2, …, an> 输出:max1,max2 【注:max1表示最大值,max2表示次大值】 2. 代码 for (int i = 1; i <= n; i++) { if (A[i] > max1) { max2 = max1; max1 = A[i]; } else if (A[i] > max2) { max2 = A[i]; } } 3. 算法正确性证明 算法证明所用技术:循环不变式 阅读详情

一般大家一开始想到的办法就是一次循环,记录下最大值和最小值。或者就是用两次冒泡,找到最大值和次大值。

这两种方法实践复杂度差不多都是O(2n),如果数组很长,效率还是不够高的。

注意:直接排序,再选择最大的两个值,这并不是一个好办法,因为我们只需要前两个数有序,不需要后N-2个数有序。

冒泡方法我就不帮大家实现了。编程的细节要注意,数组a只是个示例,如果有负值,max和second_max的初始化要最小,以免出错。

int main(int argc, char* argv[])
{
	int a[] = {1,2,3,4,5,6,7,8,9};
	int max = 0;
	int second_max = 0;
	for (int i = 0; i < 9; i++)
	{
		if (a[i] > max)
		{
			second_max = max;
			max = a[i];
		}
		else if (a[i] > second_max)
		{
			second_max = a[i];
		}
	}
	cout << max << endl;
	cout << second_max << endl;
	
	return 0;
}

我们继续思考,最大值和次大值其实就是要两个排序结果,在排序中我们当然有更快的算法(线性排序算法,归并,快速,堆排序),我们有没有办法使用这些方法呢?

想弄清楚上面的问题,我们再看一个此问题的延伸问题,也是很典型的题,编程之美上有的!


查找最大无序量元素中最大的K个数。

这篇文章分析的很棒:http://blog.youkuaiyun.com/xiaoding133/article/details/8037086。


看完以后发现第一种方法,就是我们前面所想到的。

第二种方法,依赖快速排序所选择的值,平均复杂度为O(N*logK),在K为2的时候

java代码-1.定义一个一维数组,求出数组的最大值,最小值,平均值。 立即下载

相关推荐

腾讯云DBA面试(一面)

在第二阶段,根据RM返回的结果,如果涉及分布式事务的所有RM都返回可以提交, 则TM给RM发送commit的命令,每个RM实现自己的提交,同时释放锁和资源,然后RM反馈提交成功, TM完成整个分布式事务;根据事务所处的阶段,可以回滚到具体的版本,实现一致性。1.并发执行的事务,在prepare阶段,redo log先写文件缓存,第一个领头的事务,在等待n个事务后, 在第一个事务去刷写磁盘时,会把同组的其他的事务,也一起刷写到磁盘上,这样就减少了刷盘的次数,降低了磁盘的IOPS。分布式锁是怎么实现的?

u012565458的博客 1977

飞思卡尔16位单片机(二)——CodeWarrior开发环境搭建及新建、调试工程

一、安装CodeWarrior 飞思卡尔16位单片机的开发环境为CodeWarrior5.1,这个软件安装比较简单,软件的安装文件可以从相应的网站上下载。安装CodeWarrior所需要的电脑的硬件资源也比较宽泛,目前一般的电脑都可以满足这个要求,可以支持win10、win7等操作系统。安装过程按照按照软件的提示一步步操作即可。 二、安装USBDM驱动 USBDM是...

bigmarshal的博客 1万+

利用Ghidra与SVD插件实现STM32固件深度逆向分析

本文详细介绍了如何利用Ghidra逆向工程框架结合SVD插件,实现对STM32固件(.bin文件)的深度逆向分析。通过加载描述芯片外设寄存器的SVD文件,Ghidra能将晦涩的硬件地址操作转换为可读的寄存器符号,极大提升了对嵌入式固件中通信协议、安全校验等关键逻辑的分析效率。文章涵盖了从Java环境搭建、工具配置到实战逆向解析的完整流程。

peach的博客 944

别再死记硬背了!用TwinCAT 3手把手教你配置EtherCAT伺服驱动的PDO映射(DS402协议)

本文详细介绍了如何使用TwinCAT 3配置EtherCAT伺服驱动的PDO映射(DS402协议),涵盖环境准备、设备扫描、PDO映射实战及高级技巧。通过具体操作步骤和常见问题排查,帮助工程师快速掌握EtherCAT通信配置,提升运动控制系统的效率和稳定性。

weixin_29185493的博客 322

Android13 CarPowerManagementService onApPowerStateChange流程分析

如下为CarPower上电的流程图:下面我们从代码角度分析:在CPMS的init方法中会调用onApPowerStateChange(CpmsState.WAIT_FOR_VHAL, CarPowerManager.STATE_WAIT_FOR_VHAL); 设置ApPowerState为STATE_WAIT_FOR_VHAL: 在onApPowerStateChange中调用PowerHandler 的handlePowerStateChange方法: 在handlePowerStateChang

liuning1985622的博客 925

windows下使用Nginx搭建Rtmp流媒体服务器,实现视频直播功能

一、环境介绍 操作系统:win10 64位系统 Linux下搭建Nginx搭建Rtmp流媒体服务器方法请看这里:https://blog.youkuaiyun.com/xiaolong1126626497/article/details/105378894 二、流媒体服务器介绍 流媒体服务器的主要功能是以流式协议(RTP/RTSP、MMS、RTMP等)将视频文件传输到客户端,供用户在线观看;也可从视频采集、压缩软件接收实时视频流,再以流式协议直播给客户端。 nginx服务器是开源的高性能的http服务器,反向

1万+

图像做旧算法原理及代码解释

该图像做旧算法主要通过一系列的图像处理操作来模拟旧照片的效果。整体流程包括:首先对输入图像进行颜色调整,降低饱和度并增加黄色调以营造出旧照片的色彩风格;接着添加高斯噪声来模拟旧照片可能存在的颗粒感;最后通过在图像上随机绘制线条来模拟旧照片的划痕和瑕疵。综上所述,该图像做旧算法通过对颜色的调整(包括饱和度降低、色相偏移)、添加高斯噪声以及模拟划痕和瑕疵等一系列操作,从多个方面模拟了旧照片的特征。

m0_44975814的博客 901

GEE 案例:利用多源遥感数据计算RUSLE(Revised Universal Soil Loss Equation)土壤侵蚀

该数据集提供了全球范围内以250至500米的空间分辨率获取的多光谱图像数据,用于监测地表覆盖和变化。RUSLE模型的基本原理是通过考虑土壤侵蚀的主要驱动因素,来估计土壤侵蚀的速率。该数据集提供了全球范围内以10至60米的空间分辨率获取的多光谱图像数据,用于监测地表覆盖和变化。它对农业和土地资源管理者提供了一种评估和预测土壤侵蚀风险的工具,以制定适当的土壤保护措施和决策。2. soil(土壤)是来自OpenLandMap的土壤纹理分类数据,使用了USDA(美国农业部)土壤纹理分类系统。

此星光明博客 803

IEM模型,地表粗糙度模拟

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

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...

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

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

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

上一篇: 数据结构面试题总结
下一篇: 数据结构面试题总结2——数组:求出现次数超过一半的元素
B_Allen
博客等级 码龄12年 4粉丝 11原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值