leetcode : 321. Create Maximum Number : 有点难度的贪心法

【LeetCode】321. 拼接最大数 在每一步中都要考虑后续可能的最大值保持原数组的相对顺序正确处理边界情况。 阅读详情

321. Create Maximum Number

My Submissions
Total Accepted: 4587  Total Submissions: 22666  Difficulty: Hard

Given two arrays of length m and n with digits 0-9 representing two numbers. Create the maximum number of length k <= m + n from digits of the two. The relative order of the digits from the same array must be preserved. Return an array of the k digits. You should try to optimize your time and space complexity.

Example 1:

nums1 = [3, 4, 6, 5]
nums2 = [9, 1, 2, 5, 8, 3]
k = 5
return [9, 8, 6, 5, 3]

Example 2:

nums1 = [6, 7]
nums2 = [6, 0, 4]
k = 5
return [6, 7, 6, 0, 4]

Example 3:

nums1 = [3, 9]
nums2 = [8, 9]
k = 3
return [9, 8, 9]


开始看题目,没有想法,肯定不会是暴力搜索所有可能的拼接。后来想到:如果能分别从两个数组中选出候选子集,那么就应该能够根据类似归并的样子,将其拼接成最大数组。但是,如何从一个数组中选出候选子集。瞄了一眼提示才知道:长度为subK候选子集就是在子数组中最大的子数组。
1.推论:假设数组x和数组y分别选出长度是r的subX和长度是(k-r)的subY组成的数组Z最大,并且保证元素保持原有的顺序(元素o在subX中哪些元素前后,在Z中仍然保持这样的顺序)。那么subX和subY分别是X,Y的固定长度的最大数组
原因很简单:贪心法证明,假设 subX是拼接成最大数组Z的子数组,如果subX不是X的最大数组,那么存在subXX是X数组在固定长度的最大数组。subX和subY可以拼接成Z1,那么由subXX的数组元素来替换subX拼接成Z2,很明显Z2一定大于Z1。因此subX不是拼接成最大数组Z的子数组,与假设矛盾。因此, subX是X的最大数组。

既然知道subX是X中长度为r的最大数组,找出这个数组只要在元素的可能范围内选取最大元素,即可贪心法找出。

问题的下一步是:如何将两个最大数组合并成一个最大数组。开始的想法是:反正所有元素都要使用,使用类似归并法的方法,将大值尽可能排在前面即可。整体思路是对的,但是有个致命的bug:当遇到相等的比较,那么使用哪一个?一开始没有意识到这个问题,随便是用哪一个,结果wrong了好久。最后终于意识到,选择哪一个结果不一样的:
例如:
案例1:
5,3
5,8
案例2:
5,5,8
5,8
案例3:
5
5,8
案例4:
5,5,3,7,9
5,5,3,7,8
等考虑完成这些情况后,调试AC
public class Solution {
    public int[] submax(int[]numx,int subk){
		if(subk>numx.length||subk==0)
			return null;
		if(subk==numx.length)
			return numx;
		int[] subre=new int[subk];
		int left=0,right=numx.length-subk;
		for(int i=0;i<subk;i++){
			int max=Integer.MIN_VALUE;
			int maxIndex=-1;
			for(int j=left;j<=right;j++){
				if(max<numx[j]){
					max=numx[j];
					maxIndex=j;
				}
			}
			if(maxIndex!=-1){
				subre[i]=max;
				left=maxIndex+1;
				right++;
			}
		}
		return subre;
	}
	public int[] merge(int[] sub1,int[] sub2){
		if(sub1==null||sub2==null)
			return sub1!=null?sub1:sub2;
		int len1=sub1.length;
		int len2=sub2.length;
		int len=len1+len2;
		int[] mergeList=new int[len];
		int i=0,j=0;
		int index=0;
		while(i<len1&&j<len2){
			if(sub1[i]<sub2[j])
			    mergeList[index++]=sub2[j++];
			else {
				if(sub1[i]>sub2[j])
					mergeList[index++]=sub1[i++];
				else {
					int equalNum;
					boolean find=false;
					for(equalNum=1;i+equalNum<len1&&j+equalNum<len2;equalNum++){
						if(sub1[i+equalNum]!=sub2[j+equalNum]){
							find=true;break;
						}
					}
					if(!find&&(i+equalNum<len1||j+equalNum<len2))
						find=true;
					if(find){
						int whichone=0;
						if(i+equalNum>=len1||j+equalNum>=len2)
							whichone=i+equalNum<len1?1:2;
						else {
							whichone=sub1[i+equalNum]<sub2[j+equalNum]?2:1;
						}
						mergeList[index++]=whichone==1?sub1[i++]:sub2[j++];
					}
					else {
						mergeList[index++]=sub1[i++];
					}
				}
			}
		}
		while(i<len1)
			mergeList[index++]=sub1[i++];
		while(j<len2)
			mergeList[index++]=sub2[j++];
		return mergeList;
	}
	public int comparIntList(int[] first,int[] second){
		if(first.length!=second.length)
			return first.length-second.length;
		for(int i=0;i<first.length;i++)
			if(first[i]!=second[i]){
				return first[i]-second[i];
			}
		return 0;
	}
	public int[] maxNumber(int[] nums1, int[] nums2, int k) {
		int[] re=new int[k];
		int[] subre1,subre2;
		int len1=nums1.length;
		int len2=nums2.length;
		if(k>len1+len2)
			return null;
		int minNum1=k-len2<0?0:k-len2;
		int maxNum1=len1<k?len1:k;
		for(int i=minNum1;i<=maxNum1;i++){
			subre1=submax(nums1, i);
			subre2=submax(nums2, k-i);
			int[] temp=merge(subre1,subre2);
			if(i==minNum1||comparIntList(temp,re)>0){
				System.arraycopy(temp, 0, re, 0, k);
			}
		}
		return re;
	}
}

实际上,针对相等比较的情况,需要比较的是剩余数组的大小,然后对大的数组,压一个元素进结果数据。隔壁家的代码就是精炼
public int[] maxNumber(int[] nums1, int[] nums2, int k) {
    int n = nums1.length;
    int m = nums2.length;
    int[] ans = new int[k];
    for (int i = Math.max(0, k - m); i <= k && i <= n; ++i) {
        int[] candidate = merge(maxArray(nums1, i), maxArray(nums2, k - i), k);
        if (greater(candidate, 0, ans, 0)) ans = candidate;
    }
    return ans;
}
private int[] merge(int[] nums1, int[] nums2, int k) {
    int[] ans = new int[k];
    for (int i = 0, j = 0, r = 0; r < k; ++r)
        ans[r] = greater(nums1, i, nums2, j) ? nums1[i++] : nums2[j++];
    return ans;
}
public boolean greater(int[] nums1, int i, int[] nums2, int j) {
    while (i < nums1.length && j < nums2.length && nums1[i] == nums2[j]) {
        i++;
        j++;
    }
    return j == nums2.length || (i < nums1.length && nums1[i] > nums2[j]);
}
public int[] maxArray(int[] nums, int k) {
    int n = nums.length;
    int[] ans = new int[k];
    for (int i = 0, j = 0; i < n; ++i) {
        while (n - i + j > k && j > 0 && ans[j - 1] < nums[i]) j--;
        if (j < k) ans[j++] = nums[i];
    }
    return ans;
}




Quartus II 13.1 出现 ‘‘can‘t find design entity <Filename>‘‘ 问题的解决方法 Quartus II 13.1 出现 ''can't find design entity '' 问题的解决方法 阅读详情

相关推荐

MD5算法 C语言 (从OpenSSL库中分离算法:一)

从OpenSSL库中分离算法-MD5算法 OpenSSL简介: OpenSSL 是用于传输层安全性 (TLS) 和安全套接字层 (SSL) 协议的一个强大、商业级和功能齐全的工具包,它也是一个通用的密码学库。包含有RSA、SM4、DES、AES等诸多加密算法。 OpenSSL GitHub地址如下: GitHub - openssl/openssl: TLS/SSL and crypto library 在日常的开发工作中,有时只想用OpenSSL库中的一种算法,此时调用整个OpenSSL库,往往是没必要的

逆光倾城的博客 4041

leetcode:321. 拼接最大数

这道题给了我们两个数组,里面的数字是无序的,又给我们一个k值并且k

OceanStar的博客 1082

HFSS之天线设计实例

目录 矩形微带天线 微带天线尺寸计算 微带线的3个关键指标如以下 HFSS设计流程 新建工程并设置求解类型 天线建模 添加求解设置和扫频设置 天线建模步骤 谐振点查看 优化设计 查看天线分析结果 3D增益 Smith圆图 S参数 驻波比 ​ 平面增益 方向性系数\增益\轴比 矩形微带天线 微带天线的概念首先是由Deschamps于1953年提出来的,经过20年左右的发展,Munson和Howell于20世纪70年代初期制造出来了实际的微带天线 一个简单的...

ASH_GUARDIAN的博客 1万+

【LeetCode】321. 拼接最大数(贪心+单调栈类型题)

LeetCode算法题:单调栈+贪心

weixin_43894455的博客 1249

MOSFET开关损耗全面讲解:从原理到优化策略

深入剖析MOSFET开关损耗的产生机制,结合实际应用场景,讲解如何通过驱动设计和电路优化降低损耗,提升系统效率。重点关注mosfet在高频开关下的表现与热管理。

weixin_29476595的博客 1066

PyTorch模型生产部署:ONNX/Triton导出与高可用架构实战

机器学习模型部署本质是训练环境与生产环境之间的运行时契约建立过程,涉及序列化协议、推理引擎兼容性、动态批处理及资源隔离等核心问题。ONNX凭借标准化算子集和跨框架支持,成为平衡兼容性、性能与可维护性的首选导出格式;Triton Inference Server则通过原生多框架支持、动态batching和热加载能力,显著提升GPU利用率与服务SLA保障水平。在金融风控、电商推荐等高要求场景中,基于ONNX+Triton+K8s的分层架构可稳定支撑千级QPS与毫秒级P95延迟,同时满足模型热更新、可观测性与版本

weixin_33857679的博客 457

LeetCode第321题拼接最大数

321. 拼接最大数 题目: 给定长度分别为 m 和 n 的两个数组,其元素由 0-9 构成,表示两个自然数各位上的数字。现在从这两个数组中选出 k (k <= m + n) 个数字拼接成一个新的数,要求从同一个数组中取出的数字保持其在原数组中的相对顺序。 求满足该条件的最大数。结果返回一个表示该最大数的长度为 k 的数组。 说明: 请尽可能地优化你算法的时间和空间复杂度。 示例 1: 输入: nums1 = [3, 4, 6, 5] nums2 = [9, 1, 2, 5, 8, 3] k = 5

qq_41967623的博客 642

打开电脑自动弹窗问题:无法为文件‘D:\Config.Msi\*.rbf‘设置文件安全。错误:5。请确认...如何解决?| 提供多种解决方案,亲测有效!

🏆本文收录于 《全栈Bug调优(实战版)》 专栏,该专栏专注于分享我在真实项目开发中遇到的各类疑难Bug及其深层成因,并系统提供高效、可复现的解决思路和实操方案。无论你是刚入行的新手开发者,还是拥有多年项目经验的资深工程师,本专栏都将为你提供一条系统化、高质量的问题排查与优化路径,助力你加速成长,攻克技术壁垒,迈向技术价值最大化与职业发展的更高峰🚀!

**My Coding Family** 2941

【算法】Create Maximum Number 创建最大数

【算法】Create Maximum Number 创建最大数题目解题思路代码实现 题目 Given two arrays of length m and n with digits 0-9 representing two numbers. Create the maximum number of length k <= m + n from digits of the two. The ...

无良剑&染的博客 476

多模态脑区细分图谱 HCP-MMP v1.0, Glasser et al. 2016 皮层和皮下区域,简写和全称对应关系

人类连接组计划多模态脑区细分图谱(HCP-MMP)提供了对人类大脑皮层区域的非常有用的细分(Glasser et al. 2016a, b)。图谱是多模态的,因为每个区域都是根据四个标准的组合定义的,包括结构(T1加权/T2加权髓鞘含量和皮层厚度图)、静息态功能连接、基于任务的激活和拓扑地形组织。HCP-MMP v1.0图谱包含每个半球180个皮层区域,基于210名参与者的分析。

从事脑科学核磁共振方法学研究,在Nature communications等权威期刊发表研究论文,熟练掌握磁共振处理方法和统计学方法,欢迎大家和我交流。 2655

Unreal5从入门到精通 专栏目录

欢迎来到“UE5从入门到精通”专栏!在这里,我们将带您踏上一段精彩的旅程,深入探索虚幻引擎5(Unreal Engine 5)的无限可能。不论您是游戏开发的新手,还是希望提升技能的开发者,这里都有适合您的内容。基础知识:了解虚幻引擎5的界面、功能和基本操作,为您的学习打下坚实的基础。项目实战:通过实际项目案例,帮助您从理论走向实践,真实体验游戏开发的每个环节。高级技巧:分享各种高级功能和技巧,包括蓝图、C++编程、材质编辑、光照和渲染等,让您能够创作出更具专业水准的作品。

TxNet 3023

LeetCode-321.拼接最大数、单调栈

给定长度分别为 m 和 n 的两个数组,其元素由 0-9 构成,表示两个自然数各位上的数字。现在从这两个数组中选出 k (k <= m + n) 个数字拼接成一个新的数,要求从同一个数组中取出的数字保持其在原数组中的相对顺序。 求满足该条件的最大数。结果返回一个表示该最大数的长度为 k 的数组。 说明: 请尽可能地优化你算法的时间和空间复杂度。 示例 1: 输入: nums1 = [3, 4, 6, 5] nums2 = [9, 1, 2, 5, 8, 3] k = 5 输出: [9, 8, 6, .

编程猿来如此 506

Matlab可调用MODTRAN5封装器之Mod5

MODTRAN 是一个计算地球大气中电磁辐射传输的软件代码。MODTRAN是通过使用具有严格格式的输入文本文件来控制的。这个文件被称为“tape5”,扩展名为.tp5或.ltn。手工创建或编辑这个文件是不方便的。Mod5提供了一组函数来简化MODTRAN用例的处理。这些方法包括将tape5文件格式读取到Mod5类“实例”或“对象”中,更改文件中描述的案例实例,将tape5格式写回文件,在案例上运行MODTRAN并将MODTRAN输出文件中的各种结果读取回Matlab。还有许多绘图方法可用。

qq_19512613的博客 3260

LeetCode题练习与总结:拼接最大数--321

本文详细解析了一个利用两个整数数组创建最大数的问题,介绍了贪心算法、双指针技术和递归逻辑等知识点,并给出了Java代码实现及其时间复杂度和空间复杂度分析。

一直学习永不止步 1236

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

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

LeetCode第 321 题:拼接最大数(C++)

321. 拼接最大数 - 力扣(LeetCode) 贪心算法,每次都尽可能地从可选范围内选择最大的数字。因为要保持元素的相对顺序,可选范围即为使得剩下的元素个数加上已选的元素依然有 k 个。 但是这题难在两个数组中有重复元素,比如示例 3 里面,两个数组里面都有元素 9 ,到底应该选择哪个 9 呢?只能根据后面的元素进行判断,这时可以写一个递归函数,将后面的元素作为新的数组进行选择,但是如果重复元素很多,递归栈就会很深。 那么换个思路,我们一共需要选择 k 个数,假设把这 k 个数分为两份,一份来自nums

zj 1545

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

Create Maximum Number

Given two arrays of lengthmandnwith digits0-9representing two numbers. Create the maximum number of lengthk <= m + nfrom digits of the two. The relative order of the digits from the same ar...

futangxiang4793的博客 383

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

Python | Leetcode Python题解之第321题拼接最大数

Python | Leetcode Python题解之第321题拼接最大数

Mopes__的博客 528

LeetCode 321 拼接最大数 HERODING的LeetCode之路

给定长度分别为 m 和 n 的两个数组,其元素由 0-9 构成,表示两个自然数各位上的数字。现在从这两个数组中选出 k (k <= m + n) 个数字拼接成一个新的数,要求从同一个数组中取出的数字保持其在原数组中的相对顺序。 求满足该条件的最大数。结果返回一个表示该最大数的长度为 k 的数组。 说明: 请尽可能地优化你算法的时间和空间复杂度。 示例 1: 输入: nums1 = [3, 4, 6, 5] nums2 = [9, 1, 2, 5, 8, 3] k = 5 输出: [9, 8, 6, 5

HERODING23的博客 265

LeetCode321 Create Maximum Number

Given two arrays of lengthmandnwith digits0-9representing two numbers. Create the maximum number of lengthk <= m + nfrom digits of the two. The relative order of the digits from the same ar...

李歇特冯-兹拜因巴哈的博客 192

leetcode笔记—生成最大的 数组Create Maximum Number

给定两给数组,从中选取K个使这K个在原始数组中的顺序不变,使数组最大 思路:涉及到三个函数:1.取数组中k个最大的元素,顺序不变;                                              2.合并两个数组,顺序不变,使最大;                                              3.比较两个数组的大小; class So

ldon的博客 536

Leetcode 321. Create Maximum Number

这道题的步骤如下: 1.将k拆分成两个数i,k-i,分别表示从nums1,nums2中取出的数个数 2.从nums1, nums2中取出相应个数的最大的数 3.将这两个最大的数merge成一个数 4.遍历所有的k拆分情况,得到最终Maximum Number 对于步骤2,如何从一个数组中取出给定个数(记作M)的最大数,需要用递减栈的思想: 初始化stack, 遍历数组中的数nums...

I_ren的博客 238

Create_Maximum_Number

题目描述: Given two arrays of length m and n with digits 0-9 representing two numbers. Create the maximum number of length k <= m + n from digits of the two. The relative order of the digits from the sam

numbstorm的博客 253

leetCode321:拼接最大数

目录 一、题目描述 二、解题思路 三、代码实现 一、题目描述 给定长度分别为m和n的两个数组,其元素由0-9构成,表示两个自然数各位上的数字。现在从这两个数组中选出 k (k <= m + n)个数字拼接成一个新的数,要求从同一个数组中取出的数字保持其在原数组中的相对顺序。 求满足该条件的最大数。结果返回一个表示该最大数的长度为k的数组。 说明: 请尽可能地优化你算法的时间和空间复杂度。 示例1: 输入: nums1 = [3, 4, 6, 5] nums2 =...

三中两明的博客 589

Leetcode321. 拼接最大数——单调栈的使用

文章目录前言一、题目描述1. 问题陈述2. 解题思路二、从单个数组中获得最大数三、合并使结果数最大四、完整代码(python版)总结 前言 这篇博文主要参考leetcode中的一篇题解一招吃遍力扣四道题,题解的作者详细总结了针对该类型题目的思路,以三道题目为例,讲解了如何用单调栈求解此类题目。Leetcode321题是其中的一道,属于困难题目,它的基本思想仍然是单调栈,不过在此基础上还需要一些后续步骤,才能求解最终答案。 原题解已经写的比较清楚,这里就是自己的一个小回顾。大家可以看原题解,有配图好理解~

lijianyi0219的博客 1535

leetcode321. Create Maximum Number(321. 拼接最大数)/单调栈

文章目录题目:321. 拼接最大数基本思想:单调栈 题目:321. 拼接最大数 Given two arrays of length m and n with digits 0-9 representing two numbers. Create the maximum number of length k <= m + n from digits of the two. The relative order of the digits from the same array must be pres

yyf_blog 556

LeetCode 321. 拼接最大数 单调栈解题

去除重复字母(困难) 拼接最大数(困难) 移掉 K 位数字(中等) 不同字符的最小子序列(中等) 这四道题都可以使用单调栈的思想来解决, 单调栈即为栈中元素为单调递增或者单调递减,而且在构建栈的时候可以保持原数组中的元素相对位置。其中单调性的保证是一个动态调整的过程,即当前插入元素时需要向前找是否影响了前面的元素结构,如果有影响则需要在前面的栈中弹出受到影响的元素。 这四道题中最难的是321,它涉及了两个数组,需要分别在两个数组中构建最大子序列,然后想办法把这两个序列拼接成一个。 拼接最大数 给定长度分别.

u010968350的博客 357
上一篇: leetcode : 327. Count of Range Sum : 连续和在指定区间内
下一篇: leetcode :316 Remove Duplicate Letters : 贪心+递归搜索
smileyk
博客等级 码龄16年 3粉丝 63原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值