题目

  • 输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。
  • 例如输入数组 [3,32,321],则打印出这 3 个数字能排成的最小数字 321323。
  • 数据范围

数组长度 [0,500]。

  • 注意:输出数字的格式为字符串。

示例

  • 输入:[3, 32, 321]
  • 输出:321323

代码

class Solution {
public:
    static bool myCmp(int &a, int &b) {
        auto ab = to_string(a) + to_string(b) ,ba = to_string(b) + to_string(a);
        return ab < ba;
    }
    string printMinNumber(vector<int>& nums) {
        string str;
        if(!nums.size()) return str;
        sort(nums.begin(), nums.end(), myCmp);
        for(auto data : nums) {
            str += to_string(data);
        }

        return str;    
    }

};

代码分析:关键在于定义了这个比较器

    static bool myCmp(int &a, int &b) {
        auto ab = to_string(a) + to_string(b) ,ba = to_string(b) + to_string(a);
        return ab < ba;
    }

确保两两拼接的字符串总是比逆置的字符串要小。

题目把数组排成最小的数

最后修改:2022 年 01 月 31 日 10 : 20 AM
如果我的文章对你有用,请随意赞赏