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.
思路:
我们利用排序函数按照我们的规定将nums重新排序。在具体操作的时候需要注意,我们可以直接比较整型数据,也可以比较string类型的数据。
1 比较整型数据
class Solution {
public:
static bool compare(int a, int b) {
if (a == 0) return false;
if (b == 0) return true;
long long ap = a, bp = b;
for (int i = a; i; i /= 10) bp *= 10;
bp += a;
for (int i = b; i; i /= 10) ap *= 10;
ap += b;
return ap > bp;
}
string largestNumber(vector<int>& nums) {
sort(nums.begin(), nums.end(), &compare);
string res;
for (auto i : nums) {
string tmp = to_string(i);
if (i == 0) {
if (res.empty()) res += tmp;
else if (res != "0") res += tmp;
else continue;
}
else res += tmp;
}
return res;
}
};
2 比较string类型数据
class Solution2 {
public:
static bool com(string a, string b) {
return (a + b) > (b + a);
}
string largestNumber(vector<int>& nums) {
vector<string> ns;
for (auto i : nums) { ns.push_back(to_string(i)); }
sort(ns.begin(), ns.end(), &com);
string res;
for (auto s : ns) {
res += s;
}
if (res[0] == '0') return "0";
else return res;
}
};