原题地址

 

先将数字转成字符串,然后排序,让能够组成更大数字的字符串放在前面,最后拼接成完整的字符串即可。

有种很巧妙的方法判断两个字符串的大小关系,假设两个字符串是A,B,则比较AB和BA,若AB比BA大,说明A应该放在前面,即A<B,其他同理。

 

代码:

 1 string largestNumber(vector<int> &num) {
 2         string res;
 3         
 4         vector<string> strs;
 5         for (auto n : num)
 6             strs.push_back(to_string(n));
 7 
 8         sort(strs.begin(), strs.end(), [](string &a, string &b) {return (a + b) > (b + a);});
 9 
10         for (auto str : strs) {
11             if (str == "0" && res.empty())
12                 continue;
13             res += str;
14         }
15     
16         return res.empty() ? "0" : res;
17 }

 

相关文章:

  • 2022-12-23
  • 2021-09-02
  • 2022-03-02
  • 2021-08-22
  • 2021-09-22
  • 2022-03-03
猜你喜欢
  • 2021-08-30
  • 2021-12-02
  • 2021-05-24
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-14
相关资源
相似解决方案