輸入一個正整數數組,把數組裏所有數字拼接起來排成一個數,打印能拼接出的所有數字中最小的一個。
示例 1:
輸入: [10,2]
輸出: "102"
示例 2:輸入: [3,30,34,5,9]
輸出: "3033459"
提示:
0 < nums.length <= 100
說明:輸出結果可能非常大,所以你需要返回一個字符串而不是整數
拼接起來的數字可能會有前導 0,最後結果不需要去掉前導 0
思路
將數值轉換成string,然後利用sort來對字符串進行排序,
同時利用了strcmp的比較原理:用相應位置的ASCII碼來比較
class Solution {
public:
// 函數cmp如果返回false的話sort就會交換a和b的位置,反之則不交換
static bool cmp(string a, string b){
return strcmp((a+ b).c_str(), (b+ a).c_str())== -1;
}
string minNumber(vector<int>& nums) {
// 邊界判斷
if(nums.empty()) return "";
// 將int轉換成string方便後面的排序和拼接
vector<string> num;
int size= nums.size();
for(int i= 0; i< size; i++)
num.push_back(to_string(nums[i]));
// 排序
sort(num.begin(), num.end(), cmp);
// 拼接
string result= "";
for(int i= 0; i< size; i++)
result+= num[i];
return result;
}
};