剑指Offer(牛客版)--面试题45:把数组排成最小的数

题目描述:输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3, 32, 321},则打印出这3个数字能排成的最小数字321323。

 

分析:

 

 

完整代码:

 

class Solution {
public:
    string PrintMinNumber(vector<int> numbers) {
        //声明一个变量 lenght 来获取 numbers 的个数
        int length = numbers.size();
        //声明一个变量 strNumbers ,用来存放 char 类型数组
        string strNumbers = "";
        //检查输入的合法性
        if(numbers.empty() || length  <= 0)
            return strNumbers;
        //声明一个字符串容器,用来存放
        vector<string> array;
        //遍历整个数组的元素
        for(int i = 0; i < length; ++i)
            //将 numbers 中的元素压入到 array 中
            array.push_back(to_string(numbers[i]));
        // 将 array 中的元素,以确定的顺序排列
        sort(array.begin(), array.end(), compare);
        
        //将 array 中的数字压入到strNUmbers 中
        for(int j = 0; j < array.size(); ++j)
            strNumbers.append(array[j]);
        //返回最小的数
        return strNumbers;
        
    }

private:
    //比较两个字符串的大小
    static bool compare(string strNumbers1, string strNumbers2)
    {
        //声明一个字符串变量,将 strNumbers1 的元素复制到 Strcombine1 中
        string Strcombine1 = strNumbers1;
        //将 strNumbers2 的元素连接到 Strcombine1 的尾部
        Strcombine1.append(strNumbers2);

        //声明一个字符串变量,将 strNumbers2 的元素复制到 Strcombine2 中
        string Strcombine2 = strNumbers2;    
        //将 strNumbers1 的元素连接到 Strcombine2 的尾部
        Strcombine2.append(strNumbers1);
            
        //比较 Strcombine1 和 Strcombine2 的大小
        return Strcombine1 < Strcombine2;
    }
};

相关知识点:

1、qsort()函数;

https://www.runoob.com/cprogramming/c-function-qsort.html

2、strcpy函数;

https://www.runoob.com/cprogramming/c-function-strcpy.html

3、strcat函数;

https://www.runoob.com/cprogramming/c-function-strcat.html

4、strcmp函数

https://blog.csdn.net/zhao_fu_lu/article/details/20392239

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值