lintcode: Largest Number

来源:互联网 发布:多系统数据共享 编辑:程序博客网 时间:2024/05/21 15:30

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

Notice

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

Example

Given [1, 20, 23, 4, 8], the largest formed number is 8423201.

Challenge

Do it in O(nlogn) time complexity.


class Solution {    private:    static bool cmp(const string &a,const string &b){        string ab = a + b;        string ba = b + a;        return ab > ba;    }    public:    /**     *@param num: A list of non negative integers     *@return: A string     */    string largestNumber(vector<int> &num) {        // write your code here                vector<string> auxVtr(num.size());                for(int i : num)            auxVtr.push_back(to_string(i));                sort(auxVtr.begin(), auxVtr.end(), cmp);                string retStr = "";        for (int i=0; i<auxVtr.size(); i++)            retStr += auxVtr[i];                    if(retStr[0] == '0' && retStr.size() > 0)             return "0";                    return retStr;    }};


0 0