58. 把数组排成最小的数

 

 思路: https://www.cnblogs.com/lliuye/p/9159152.html

2 思路描述:

 

 

 

 

sort(begin,end,cmp),cmp参数默认升序。

⑤vector进行排序
sort(nums.begin(),nums.end());

 

 

static bool cmp(int &a, int &b) {
    string ab = to_string(a) + to_string(b);
    string ba = to_string(b) + to_string(a);
    return ab < ba;
}
string printMinNumber(vector<int>& nums) {
    string res;
    if(nums.empty()) return res;
    sort(nums.begin(),nums.end(),cmp);//对数组元素进行降序排序,构造排序函数cmp
    for(int i = 0;i<nums.size();i++)
    {
        res += to_string(nums[i]);
    }
    return res;
}

 注意了bool前的static不能少,否则编译通不过

 

另一种写法

class Solution {
public:
    string PrintMinNumber(vector<int> numbers) {
        int length = numbers.size();
        if(length == 0){
            return "";
        }
        sort(numbers.begin(), numbers.end(), cmp);
        string res;
        for(int i = 0; i < length; i++){
            res += to_string(numbers[i]);
        }
        return res;
    }
private:
    // 升序排序
    static bool cmp(int a, int b){
        string A = to_string(a) + to_string(b);
        string B = to_string(b) + to_string(a);
        return A < B;
    }
};

 

posted @ 2020-02-17 20:01  靖愁  阅读(163)  评论(0编辑  收藏  举报