給定非負整數數組,重新排列順序使拼接成的數字最大。結果可能很大,返回字符串。
輸入:[3, 30, 34, 5, 9] 輸出:"9534330"
對於兩個數字字符串 a、b,比較 a+b 與 b+a 的字典序:
a+b > b+a → a 排在 b 前面"3" vs "30":"330" > "303" ⇒ 3 在前class Solution {
public:
static bool cmp(const string& a, const string& b) {
return a + b > b + a;
}
string largestNumber(vector<int>& nums) {
vector<string> strs;
for (int n : nums) strs.push_back(to_string(n));
sort(strs.begin(), strs.end(), cmp);
if (strs[0] == "0") return "0"; // 全零情況
string res;
for (auto& s : strs) res += s;
return res;
}
};
"0" 而非 "000..."a+b > b+a 可傳遞)