LeetCode: 179. Largest Number
LeetCode: 179. Largest Number
题目描述
Given a list of non negative integers, arrange them such that they form the largest number.
Example 1:
Input: [10,2]
Output: "210"
Example 2:
Input: [3,30,34,5,9]
Output: "9534330"
Note: The result may be very large, so you need to return a string instead of an integer.
解题思路
根据两个相邻的数组成的数的大小,将所有的数字排序。
AC 代码
class Solution {
static bool cmp(string lhv, string rhv)
{
return (lhv+rhv) > (rhv+lhv);
}
public:
string largestNumber(vector<int>& nums) {
vector<string> numStrs;
for(size_t i = 0; i < nums.size(); ++i)
{
numStrs.push_back(to_string(nums[i]));
}
sort(numStrs.begin(), numStrs.end(), cmp);
string ans;
for(string str : numStrs)
{
ans += str;
}
if(!ans.empty() && ans[0] == '0') ans = "0";
return ans;
}
};