未料到排序规则。排序规则为:若 x+y>y+x,则x”大于“y,反之,若x+y<y+x,则x”小于“y。 参考:剑指 Offer 45. 把数组排成最小的数(自定义排序,清晰图解)
定义内置函数规则:
class Solution {
public:
string minNumber(vector<int>& nums) {
vector<string>s;
string res;
for(auto num:nums){
s.push_back(to_string(num));
}
sort(s.begin(),s.end(),[](string&x,string&y){return x+y<y+x;});
for(auto x:s){
res+=x;
}
return res;
}
};
定义快速排序规则:
class Solution {
public:
int mid(vector<string>&s,int low,int high){ //基准值
string pivot=s[low];
while(low<high){
while(low<high&&(s[high]+pivot>=pivot+s[high])){
high--;
}
s[low]=s[high];
while(low<high&&(s[low]+pivot<=pivot+s[low])){
low++;
}
s[high]=s[low];
}
s[low]=pivot;
return low;
}
void quickSort(vector<string>&s,int low,int high){ //递归函数
if(low<high){ //若小于则进入递归
int pivot=mid(s,low,high);
quickSort(s,low,pivot-1);
quickSort(s,pivot+1,high);
}
}
string minNumber(vector<int>& nums) {
vector<string>s;
string res;
for(auto num:nums){
s.push_back(to_string(num));
}
quickSort(s,0,nums.size()-1);
for(auto x:s){
res+=x;
}
return res;
}
};