【剑指offer】【排序】45.把数组排序成最小的数
自定义排序规则
假设nums任意两个数字的字符串格式x和y,则
若拼接字符串 x + y > y + x, 则 m > n;
反之,x + y < y + x, 则 n < m;
时间复杂度:O(nlogn)
空间复杂度:O(n)
class Solution {
public:
string minNumber(vector<int>& nums) {
auto compare = [](string sa, string sb){return sa + sb < sb + sa;};
vector<string> tmp;
for(int n : nums){
tmp.push_back(to_string(n));
}
sort(tmp.begin(), tmp.end(), compare);
string ans = "";
for(string s : tmp) ans += s;
return ans;
}
};
简化
题目链接:https://leetcode-cn.com/problems/ba-shu-zu-pai-cheng-zui-xiao-de-shu-lcof/
class Solution {
public:
string minNumber(vector<int>& nums) {
sort(nums.begin(), nums.end(),
[](int a, int b)
{
return to_string(a) + to_string(b) < to_string(b) + to_string(a);
});
string res = "";
for(auto &x : nums)
res += to_string(x);
return res;
}
};
知识的价值不在于占有,而在于使用