Given a list of non negative integers, arrange them such that they form the largest number.

For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.

Note: The result may be very large, so you need to return a string instead of an integer

 

小技巧为排序中的比较函数,另外记住不能有=号

 

class Solution {
public:
    static bool compareFunc(string &s1, string& s2) {
        return s1+s2 > s2+s1;
    }
    string largestNumber(vector<int>& nums) {
        string res;
        int n = nums.size();
        vector<string> vecStr;
        for (int i = 0; i < n; i++) {
            vecStr.push_back(to_string(nums[i]));
        }
        sort(vecStr.begin(), vecStr.end(), compareFunc);
        if(vecStr[0] == "0") return "0";
        
        for (int i = 0; i < n; i++) {
            res += vecStr[i];
        }
        return res;
    }
};

 

相关文章:

  • 2021-12-20
  • 2021-09-22
  • 2021-07-05
  • 2022-03-03
  • 2021-08-22
猜你喜欢
  • 2022-01-24
  • 2021-11-15
  • 2021-09-13
  • 2021-10-01
  • 2021-08-07
相关资源
相似解决方案