leetcode 179. Largest Number
179. Largest Number
要比较拼接以后谁应该放在前面,先试着把他们拼起来就行了
然后因为正着拼和反着拼,长度一致,所以自带的string比较函数会严格比较他们的大小关系,不会因为字符串长度而误判
bool cmp(const int &a, const int &b);
class Solution {
public:
std::string largestNumber(std::vector<int> &nums) {
std::sort(nums.begin(), nums.end(), cmp);
std::string res = "";
for (auto ni : nums) {
std::string si = std::to_string(ni);
res += si;
}
if(res[0] == '0')
return "0";
else return res;
}
};
bool cmp(const int &a, const int &b) {
std::string sa = std::to_string(a);
std::string sb = std::to_string(b);
return sa + sb > sb + sa;
}