Leecode179Largest Number

来源:互联网 发布:深圳软件开发外包 编辑:程序博客网 时间:2024/06/07 04:49

179. Largest Number

DescriptionHintsSubmissionsDiscussSolution

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 is9534330.

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.


思路:这题首先将数字转换成字符串,因为字符串比较容易操作,然后将转换的字符串进行排序,排序的规则就是:如何比较两个字符串组合后的数大, 直接比较 (a + b) 和 (b + a)如果前者大,则将a放前面 b)如果后者大,则将b放在前面。

string largestNumber(vector<int>& nums) {
        string s = "";
        if(nums.empty()) return s;
        vector<string> svec;
        for(int i = 0; i < nums.size(); i++)
        {
            svec.push_back(to_string(nums[i]));
        }
        sort(svec.begin(), svec.end(), [](string a, string b){ return a + b > b + a ? true : false; });
        for(int i = 0; i < svec.size(); i++)
        {
            s += svec[i];
        }
        while(s[0] == '0') s.erase(s.begin());
        if(s.empty()) s.push_back('0');
        return s;
    }

原创粉丝点击