【剑指Offer】把数组排成最小的数
发布日期:2022-02-10 08:55:16 浏览次数:25 分类:技术文章

本文共 637 字,大约阅读时间需要 2 分钟。

题目

输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。

示例 1:

输入: [10,2]

输出: "102"
示例 2:

输入: [3,30,34,5,9]

输出: "3033459"

思路

自定义排序,一个字符串的字典序排序

排序判断规则: 设 nums 任意两数字的字符串格式 x 和 y,则

若拼接字符串 x + y > y + x ,则 m > n ;
反之,若 x + y < y + x ,则 n < m ;

代码

class Solution {public:    static bool comp(int a,int b){        string astr=to_string(a);        string bstr=to_string(b);        return astr + bstr < bstr + astr;    }    string minNumber(vector
& nums) { sort(nums.begin(),nums.end(),comp); string res = ""; for(int i = 0;i < nums.size();i++){ res = res + to_string(nums[i]); } return res; }};

 

转载地址:https://blog.csdn.net/hanmin822/article/details/105853738 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:【剑指Offer】数字序列中某一位的数字
下一篇:【剑指Offer】把数字翻译成字符串

发表评论

最新留言

感谢大佬
[***.8.128.20]2024年04月14日 08时21分07秒