- Total Accepted: 65867
- Total Submissions: 304513
- Difficulty: Medium
- Contributors: Admin
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.
Credits:
分析
关键在于怎样判断两个数字组合谁放在前面。
判断规则是 将a和b组成"ab" 和 "ba",哪个更大,说明首个数字更大
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
class Solution {
public:
string largestNumber(vector<int>& nums) {
sort(nums.begin(), nums.end(),[](int a, int b){
return to_string(a) + to_string(b) > to_string(b) + to_string(a);
});
string result;
for(auto n: nums){
result+= to_string(n);
}
// in case all the number in nums is '0'
return result[0] == '0' ? "0" : result;
}
}; |