【LeetCode刷题(中等程度)】剑指 Offer 45. 把数组排成最小的数

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

示例 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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路:我们首先可以想到全排列,找到排列中最小数字即可。但是这样的复杂度在n!。我们可以不可以再定义出一种排序顺序,如果两个数a,b(用字符表示,后面的+表示字符拼接)满足a + b < b + a,那么a就应该在b的前面。

代码实现:

class Solution {
public:
    string minNumber(vector<int>& nums) {
        vector<string> strs;
        string res;
        for(auto num:nums)
        {
            strs.push_back(to_string(num));
        }
        sort(strs.begin(),strs.end(),compare);//使用函数对象实现
        for(auto str : strs)
        {
            res += str;
        }
        return res;
    }
private:
    static bool compare(const string &a,const string &b)
    {
        return a + b < b + a;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_33197518/article/details/109059419
今日推荐