leetcode 剑指offer 45:把数组排成最小的数

剑指Offer(leetcode版) 目录剑指Offer-03 数组中重复的数字剑指Offer-04 二维数组中的查找剑指Offer-05 替换空格剑指Offer-06 从尾到头打印链表剑指Offer-07 重建二叉树剑指Offer-09 用两个栈实现队列剑指Offer-10-I 斐波那契数列剑指Offer-10-II 青蛙跳台阶问题剑指Offer-11 旋转数组的最小数字剑指Offer-12 矩阵中的路径剑指Offer-13 机器人的运动范围剑指Offer-14-I 剪绳子剑指Offer-14-II 剪绳子II剑指Offer-15 二进制中1 阅读详情

题目描述:
输入一个非负整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。
示例1:
输入: [10,2]
输出: “102”
示例 2:
输入: [3,30,34,5,9]
输出: “3033459”
思路:
首先读题目的时候,有一个地方需要注意到就是,并不是简单的对数组中的数进行了字典排序,比如示例2中30是排在3前面的,如果简单的按照字典顺序排序,3是排在30前面的,而得到的最终结果是3303459不是题目的要求。
正确的思路:优秀题解链接
1)定义一种新的排序规则:
根据本题总结出的排序规则:
若拼接字符串 x + y > y + x ,则 x “大于” y ;
反之,若 x + y < y + x ,则x “小于” y ;
2)套用到已有的排序方法中:
以套用到快排中为例:

class Solution:
    def minNumber(self, nums: List[int]) -> str:
        def quick_sort(l , r):
            if l >= r: return
            i, j = l, r`在这里插入代码片`
            while i < j:
                while strs[j] + strs[l] >= strs[l] + strs[j] and i < j: j -= 1
                while strs[i] + strs[l] <= strs[l] + strs[i] and i < j: i += 1
                strs[i], strs[j] = strs[j], strs[i]
            strs[i], strs[l] = strs[l], strs[i]
            quick_sort(l, i - 1)
            quick_sort(i + 1, r)
        
        strs = [str(num) for num in nums]
        quick_sort(0, len(strs) - 1)
        return ''.join(strs)

套用到内置函数中:

class Solution:
    def minNumber(self, nums: List[int]) -> str:
        def sort_rule(x, y):
            a, b = x + y, y + x
            if a > b: return 1
            elif a < b: return -1
            else: return 0
        
        strs = [str(num) for num in nums]
        strs.sort(key = functools.cmp_to_key(sort_rule))
        return ''.join(strs)

时间复杂度:
查找中位数 O(1) : 获取堆顶元素使用 O(1) 时间;
添加数字 O(logN) : 堆的插入和弹出操作使用 O(logN) 时间。
空间复杂度 O(N) : 其中 N 为数据流中的元素数量,小顶堆 A 和大顶堆 B 最多同时保存 N 个元素。

剑指offer 面试题45 – 把数组排成最小的数 题目描述 面试题45. 把数组排成最小的数 解法:自定义排序规则(Python) 详细参考 Krahets class Solution: def minNumber(self, nums: List[int]) -> str: def sort_rule(x, y): a, b = x + y, y + x if a > b: return 1 elif a < b: return -1 else: return 0 strs = [str(num) for 立即下载

相关推荐

HA集群 执行 hdfs haadmin -transitionToActive 失败

最近把一个单NameNode集群变更为HA集群,过程中都很顺利,nn1和nn2两个NameNode都显示standby状态,但是把nn1或者nn2切换到active状态时就会报错抛异常。 查看master上namenode启动日志,如下: Incompatible clusterID for journal Storage Directory /home/hadoop-zero/bigdat...

qq_34727158的博客 1764

【剑指offer系列】45. 把数组排成最小的数

【剑指offer系列】45. 把数组排成最小的数

姚先生的全栈之路 310

DSP28335与Vofa+上位机通信实战:SCIb配置避坑指南(附完整代码)

本文提供DSP28335与Vofa+上位机通信的实战指南,重点解析SCIb模块配置的常见问题与解决方案。针对研旭开发板的硬件连接、波特率精确计算、FIFO高效使用以及FireWater协议封装进行了详细说明,并附有完整代码,帮助开发者快速实现实时数据可视化与波形分析,提升调试效率。

weixin_29172963的博客 150

(排序) 剑指 Offer 45. 把数组排成最小的数 ——【Leetcode每日一题】

剑指 Offer 45. 把数组排成最小的数 输入一个非负整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。

weixin_43412762的博客 1058

从交换机安全配置,看常见局域网攻击

前言 构建零信任网络,自然离不开网络准入(NAC),这就涉及到交换机的一些安全测试,于是有了此文《从交换机安全配置看常见局域网攻击》。 交换机安全配置 如本文标题所说从交换机安全配置看常见的局域网攻击,那么下面提到的各种攻击方式,自然是建立在交换机安全配置之上来说的。我们通过h3c官方提供的《H3C 交换机安全加固手册》和《安全配置指导》,从这两份手册可以看出交换机支持的安全配置非常多,基本已经覆盖了各种我们熟知局域网攻击。下面就挑几个典型的攻击方式进行演示。 arp欺骗 【一>所有资源获取&lt

kali_Ma的博客 1万+

OnlyOffice Docker部署踩坑实录:解决Nginx反向代理导致的editor.bin下载失败

本文详细解析了在Docker中部署OnlyOffice时,因Nginx反向代理配置不当导致editor.bin下载失败的常见问题。通过分析问题根源,提供了从Nginx代理配置、Docker网络设置到OnlyOffice容器内部调整的完整解决方案,并分享了实战调试技巧与性能优化建议,帮助用户彻底解决这一部署难题。

wine的专栏 523

剑指 Offer 45. 把数组排成最小的数

剑指 Offer 45. 把数组排成最小的数

wacyy的博客 73

手把手教你完成基于cnn的手写数字识别系统MATLAB语言

手写数字识别是经典的 CNN 分类应用之一,常用的数据集就是 MNIST 手写数字数据集,包含 0~9 这 10 个数字的手写图片,每个数字都由 6 万幅训练图像和 1 万幅测试图像构成。为了便于直观分析,这里选择 MATLAB 工具箱提供的 DigitDataset 进行训练识别,读者也可以直接利用 MNIST 数据集或者自己设计的数据集进行实验。其中,数据集文件夹 db 如图 所示。在数据集文件夹 db 里面对每个数字都建立了子文件夹,各自包含 1000 幅 28×28 大小的二维灰度图像。

在职AI算法工程师,擅长计算机视觉,YOLO目标检测、分割等,擅长web、pyqt界面可视化,好内容持续更新中,来这里跟大家一起学习,共同进步 1368

【剑指Offer系列】45-把数组排成最小的数(sort排序字符串a+b和b+a)

使用字符串的排序

tmax52HZ的博客 200

RNA-seq分析:Step8(富集分析)

RNA-seq富集分析是一种用于分析基因表达数据中特定基因或通路是否富集的分析方法。其基本思想是比较不同基因对应的转录本/基因之间的表达差异及其对应的基因注释信息,通过统计学方法评估差异的显著性,从而确定是否存在某些特定的功能通路或基因集合富集的情况。常用的RNA-seq富集分析工具包括GOseq、KEGG(KEGG enrichment analysis)、DAVID(Database for Annotation, Visualization and Integrated Discovery)等。这

沉香best的博客 3633

如何通过单步调试的方法,找到 SAP Gateway 到底把 Fiori 应用发送的 OData 请求,投递到哪一台 ABAP 后台服务器了?

这是一个 Count 请求,得到服务器响应的数据是 204,这个 204 会以数字的形式,显示在 Fiori Launchpad tile 上。那如果当前 Gateway 系统可以连接到多台 ABAP 后台服务器,比如下图所示,可以连接 SAP S/4HANA,ERP 或者 SAP CRM,我怎么知道 SAP UI5 应用上显示的数据,到底来自哪一台 ABAP 后台服务器呢?,就是上图 ABAP 调试器里断点停留的位置,即 SAP Frontend 服务器,通过 RFC 将 OData 请求投递给。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 642

【LeetCode & 剑指offer刷题】数组题15:45 把数组排成最小的数

【LeetCode &amp; 剑指offer刷题】数组题15:45 把数组排成最小的数 【LeetCode &amp; 剑指offer 刷题笔记】目录(持续更新中...) 45 把数组排成最小的数 题目描述 输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这...

技术改变世界 854

【深度学习新浪潮】气候预测模型的研发进展一览(2025年版)

模型类型核心优势适用场景不足ARIMA(统计模型)简单高效、可解释性强短期单变量预测非线性、长时依赖建模差随机森林(机器学习)多特征融合、抗噪声中短期多因素预测空间相关性、时序趋势捕捉弱LSTM(深度学习)长时依赖建模、端到端中长期时序预测物理一致性差、数据需求量大物理知情AI物理规律约束、高可靠性极端天气、长期气候变化模型复杂、计算成本高。

专注:太空算力、AI infra、异构调度、大模型成本工程 528

Leetcode刷题:剑指offer【面试题45 把数组排成最小的数】

文章目录 【面试题45 把数组排成最小的数】 输入一个非负整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。 Leetcode题目对应位置: 面试题45:把数组排成最小的数 ...

学习 & 分享 ~ 755

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

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

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

LeetCode:剑指 Offer 45. 把数组排成最小的数(C语言)

题目描述: 输入一个非负整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。 示例 1: 输入: [10,2] 输出: “102” 示例 2: 输入: [3,30,34,5,9] 输出: “3033459” 提示: 0 < nums.length <= 100 说明: 输出结果可能非常大,所以你需要返回一个字符串而不是整数 拼接起来的数字可能会有前导 0,最后结果不需要去掉前导 0 作者:Krahets 链接:https://leetcode-cn.com/le

C/C++攻城狮 759

深度学习工具包 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 179. 最大数 & 剑指Offer: 45 把数组排成最小的数(Java解法)

剑指 Offer: 45 把数组排成最小的数; LeetCode: 179. 最大数

RAYFUXK的专栏 582

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

(python version) 剑指 offer 45. 把数组排成最小的数

题目描述 输入一个非负整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。 来源:力扣(LeetCode) 解题思路 方法一 python3 当中的自定义排序:使用 functools 模块当中的 cmp_to_key。 详细说明:python3 中自定义排序原理@知乎 是 python2 的 list.sort() 与 python3 兼容,自定义排序规则的方法。 将不同长度的字符串进行排列,例如:s = [‘52’, ‘5’, ‘50’, ‘51’]。 若使用 s

monarch 440

leetcode:剑指 Offer 45. 把数组排成最小的数【functools.cmp_to_key自定义排序】

通过自定义函数 如果x和y,xy比yx更小就返回-1,若更大返回1,否则返回0 然后根据这个返回值进行sort即可 冒泡排序的变种 总结 functools.cmp_to_key自定义排序 需要将排序关系转换成一个key值作为返回...

小楼一夜听春雨 253

剑指offer45:把数组排成最小的数

数学 字符串 排序

weixin_46266058的博客 451

剑指 Offer 45. 把数组排成最小的数 - 力扣(LeetCode)

剑指 Offer 45. 把数组排成最小的数 - 力扣(LeetCode)

Onwaier的博客 702

LeetCode剑指offer系列 45. 把数组排成最小的数

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录前言一、解题思路二、代码总结 前言 此文章用来记录LeetCode剑指offer系列 45. 把数组排成最小的数的心得 一、解题思路 首先要将数组字符串化,创建一个字符串列表strs来保存各数字的字符串格式; 由于数字是字符串格式,我们需要用CompareTo方法来比较大小; 用l表示字符串头下标,r表示字符串尾下标,i,j表示进行对比的数字下标,初始化为l,r; 排序规则: I. 当i<j时: (1)比较strs[j]

qq_42570982的博客 277
上一篇: 【双指针】leetcode 剑指offer 22:链表正倒数第k个结点
下一篇: leetcode剑指offer41:数据流中的中位数
coding_diamond
博客等级 码龄8年 8粉丝 131原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值