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

 

示例 1:

输入: [10,2]
输出: "102"
示例 2:

输入: [3,30,34,5,9]
输出: "3033459"
 

提示:

0 < nums.length <= 100
说明:

输出结果可能非常大,所以你需要返回一个字符串而不是整数
拼接起来的数字可能会有前导 0,最后结果不需要去掉前导 0

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ba-shu-zu-pai-cheng-zui-xiao-de-shu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

 

 

把给出的数进行排序,对于位数相同的直接按照从小到大排序,对于位数不同的分两种,如10和2就是10在2前面,10和102就是102在10右边,显然10102比10210小,如果是112和1121就是1121在前面关键是比较多出来的那一位。关键是编写cmp函数。

代码:

class Solution {
public:
    static bool cmp(string a,string b) {
        if(a.size() == b.size()) return a < b;
        int len = min(a.size(),b.size());
        for(int i = 0;i < len;i ++) {
            if(a[i] != b[i]) return a[i] < b[i];
        }
        int i = 0;
        if(a.size() < b.size()) {
            while(i < a.size() && b[a.size()] == b[i]) i ++;
            return b[a.size()] > b[i]; 
        }
        while(i < b.size() && a[b.size()] == a[i]) i ++;
        return a[b.size()] < a[i];
    }
    string minNumber(vector<int>& nums) {
        vector<string> num;
        for(int i : nums) {
            num.push_back(to_string(i));
        }
        sort(num.begin(),num.end(),cmp);
        string ans = "";
        for(string i : num) {
            ans += i;
        }
        return ans;
    }
};