输入一个非负整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。
示例 :
输入: [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);
}