leetcode 179. Maximum number

Given a set of non-negative integers, rearrange their order to form the largest integer.

Example 1:

input: [10,2]
output:210

Example 2:

input: [3,30,34,5,9]
output:9534330

Explanation: The output result can be very large, so you need to return a string instead of an integer.

 

I have written a comparison function for a long time, and the clock is defective. I saw this very clever comparison method on the Internet.

bool cmp(string a, string b){
  return a+b>b+a;  
}

Such a short program can achieve the largest combination, but it's still too bad.

#include<algorithm>
class Solution {
public:
    static bool cmp(string a, string b){
        return a+b>b+a;
    }
string largestNumber(vector<int>& nums) {
        vector<string> ans;
        for(int i = 0; i < nums.size(); i++) ans.push_back(to_string(nums[i]));
        sort(ans.begin(), ans.end(), cmp);
        string res = "";
        for(int i = 0; i < nums.size();i++) res += ans[i];
        if(res[0] == '0') res = "0";
    return res;
    }
};

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325277509&siteId=291194637