179-Largest Number
Description
Given a list of non-negative integers nums, arrange them such that they form the largest number and return it.
Since the result may be very large, so you need to return a string instead of an integer.
Example
1 2
| Input: nums = [10,2] Output: "210"
|
Solution
Use customized compare function in sort.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Solution { public: string largestNumber(vector<int>& nums) { vector<string> s; for (auto n : nums) s.push_back(to_string(n)); sort(s.begin(), s.end(), [](auto& x, auto& y){ string s1 = x + y; string s2 = y + x; return s1 > s2; });
if (s[0] == "0") return "0";
string ans = ""; for (auto v : s) ans += v; return ans; } };
|