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:
Since we need to decide which number is in front of another for each pair of numbers, we could come up a new rule for comparison in sort function.
This file contains 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>& num) { | |
sort(num.begin(), num.end(), [](int a, int b) { return to_string(a)+to_string(b) > to_string(b)+to_string(a); }); | |
string res; | |
for(int i=0; i<num.size(); i++) | |
res=res+to_string(num[i]); | |
return res[0]=='0' ? "0":res; | |
} | |
}; |
No comments:
Post a Comment