2017年4月29日 星期六

[LeetCode] 179. Largest Number

轉自LeetCode

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"]
code如下

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;
}
};

沒有留言:

張貼留言