leetcode 179. Largest Number

来源:互联网 发布:淘宝设计属于什么行业 编辑:程序博客网 时间:2024/06/05 19:04

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


直接利用sort的自定义排序功能。


static bool is_change(const string& a, const string& b) //如果a < b则交换{    string ab = a + b;    string ba = b + a;    return ab > ba;}class Solution {public:    string largestNumber(vector<int>& nums)     {        string ret = "";        vector<string> num;        for(auto it : nums)            num.push_back(to_string(it));                sort(num.begin(), num.end(), is_change);        for(int i = 0; i < num.size(); i++)            ret = ret + num[i];                //如果全是0则返回"0"        if (ret[0] == '0')            return "0";        return ret;      }};


原创粉丝点击