leetcode_num179_Largest Number

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.

两两比較 能够利用sort函数来排序,自己定义compare函数。即比較规则

可用vector来取代数组。easy定位

bool compare(int a,int b){
    string t1=to_string(a)+to_string(b);
    string t2=to_string(b)+to_string(a);
    return t1>t2;
}
    //return to_string(a)+to_string(b)>to_string(b)+to_string(a);
    
class Solution {
public:
    string largestNumber(vector<int> &num) {//use vector to present array
        if(num.size()<=0)
            return "";
        sort(num.begin(),num.end(),compare);
        string res;
        for(int i=0;i<num.size();i++)
            res+=to_string(num[i]);
        return res[0]=='0'?"0":res;//only elements valued 0
    }
};


原文地址:https://www.cnblogs.com/yxysuanfa/p/7098368.html