Given a list of non negative integers, arrange them such that they form the largest number.
For example, given [3, 30, 34, 5, 9] , the largest formed number is 9534330 .
Note: The result may be very large, so you need to return a string instead of an integer.
<Solution>這題是要把非負數的數字們,組成一個最大的數字
想法如下
- 先將數字都轉成字串
- 透過字串的比對,來排序字串。例如 ["30", "9"],因為 "309" < "930",所以排序結果會是 ["9", "30"]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
string largestNumber(vector<int>& nums) { | |
string ans; | |
vector<string> numStr; | |
//>> change int to string | |
for(const auto &n : nums) { | |
numStr.push_back(to_string(n)); | |
} | |
//>> sorting | |
//>> ex. "30" and "9" => "309" < "930" | |
//>> therefore, "9" comes before "30" | |
sort(numStr.begin(), numStr.end(), [](string a, string b) -> bool { | |
return a+b > b+a; | |
}); | |
//>> combine to ans | |
for(const auto &s : numStr) { | |
ans += s; | |
} | |
//>> eliminate redundant 0s | |
return (ans[0] == '0') ? "0" : ans; | |
} | |
}; |
沒有留言:
張貼留言