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.
將給定數字連接成為一個最大的數。字符串排序,排序規則如下:
對于a和b兩個數字,如果ab>ba則a應該排在b之前
注意全為0的情況
class Solution {public: static bool cmp(string &a, string &b) { return a+b > b+a; } string largestNumber(vector<int>& nums) { vector<string> res; for(int i = 0; i < nums.size(); i++) res.push_back(to_string(nums[i])); sort(res.begin(), res.end(), cmp); string ans; for(int i = 0; i < res.size() ; i++) ans += res[i]; if(ans[0] == '0') ans = '0'; return ans; }};
新聞熱點
疑難解答