class Solution {
public:
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);//后边界记着-1
string res;
for(string s : strs)
res.append(s);//append函数
return res;
}
private:
void quickSort(vector<string>& strs, int l, int r) {
//这里如果没有引用就会出错 不知道为什么
if(l >= r) return;
int i = l, j = r;
//l是pivot
while(i < j) {
//先从右往左(必须)找到第一个小于pivot的数
while(strs[j] + strs[l] >= strs[l] + strs[j] && i < j) j--;
//再从左到右找到第一个大于pivot的数
while(strs[i] + strs[l] <= strs[l] + strs[i] && i < j) i++;
//将这俩个数交换 不断重复该过程 直到i和j相遇
swap(strs[i], strs[j]);
}
//将ij的相遇点的数与pivot交换
swap(strs[i], strs[l]);
quickSort(strs, l, i - 1);//左边递归
quickSort(strs, i + 1, r);//右边递归
}
};
作者:jyd
链接:https://leetcode-cn.com/problems/ba-shu-zu-pai-cheng-zui-xiao-de-shu-lcof/solution/mian-shi-ti-45-ba-shu-zu-pai-cheng-zui-xiao-de-s-4/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
append
函数:在字符串的末尾添加字符串str。
lambda表达式
这个太妙了
class Solution {
public:
string minNumber(vector<int>& nums) {
sort(nums.begin(), nums.end(), [](int num1, int num2){
return to_string(num1) + to_string(num2)<to_string(num2) + to_string(num1);
});
string res;
for (int i : nums){
res += to_string(i);
}
return res;
}
};
运算符重载
这个题用运算符重载感觉其实没有必要 因为不需要一个结构体(一个数只有一个属性/对比华为调度题)是一种实验吧 做大厂的题真的能开阔思路
class Solution {
public:
typedef struct Node{
int t;
bool operator <(const Node & a)const{ //小于号重载
return to_string(this->t) + to_string(a.t) < to_string(a.t) + to_string(this->t);}
}num;//题干条件
public:
string minNumber(vector<int>& nums) {
num a[nums.size()];
for(int i=0;i<nums.size();i++){
a[i].t=nums[i];
}
sort(a, a+nums.size());
string res;
for(auto i:a){
res+=to_string(i.t);
}
return res;
}
};