把数组排成最小的数

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

示例 :

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

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

提示:

  • 0 < nums.length <= 100

说明:

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

思路:数字的大小,和转化成字符串后字典序的大小是一致的。所以本质上是一个排序题,对于两个字符串a、b,如果a + b < b + a,a放在b的前面,否则b放在a的前面。

//利用内置函数,自定义排序规则
string minNumber(vector<int>& nums) {
    vector<string> vec;
    for (auto it : nums) {
        vec.push_back(to_string(it));
    }
    sort(vec.begin(), vec.end(), [](string a, string b){ return a + b < b + a; });
    string res = "";
    for (auto it : vec) {
        res += it;
    }
    return res;
}

//不用内置函数,自己写了一个快速排序。题解里看的,大佬太强了。
string minNumber(vector<int>& nums) {
    vector<string> strs;
    for (int i = 0; i < nums.size(); i++)
        strs.push_back(to_string(nums[i]));
    quickSort(strs, 0, strs.size() - 1);
    string res;
    for (string s : strs)
        res.append(s);
    return res;
}
void quickSort(vector<string>& strs, int l, int r) {
    if (l >= r) return;
    int i = l, j = r;
    while (i < j) {  
        while (strs[j] + strs[l] >= strs[l] + strs[j] && i < j) j--;
        while (strs[i] + strs[l] <= strs[l] + strs[i] && i < j) i++;
        swap(strs[i], strs[j]);
    }
    swap(strs[i], strs[l]);
    quickSort(strs, l, i - 1);
    quickSort(strs, i + 1, r);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值