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.

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

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

劍指offer上面的一題,其實就是一種新的排序方法。

class Solution {
public:
    string largestNumber(vector<int> &num) {
        vector<string> tmp;
        for(auto i : num)
            tmp.push_back(to_string(i));
        sort(tmp.begin(),tmp.end(),[](string s1,string s2){return s1+s2>s2+s1;});
        
        string ans = "";
        for(auto i : tmp)
            ans = ans + i;
            
        while(ans[0]=='0' && ans.size()>1)
            ans = ans.substr(1);
        return ans;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章