Leetcode 179 Largest Number

2018-01-12 14:48:59 浏览数 (1)

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.

将给定数字连接成为一个最大的数。

字符串排序,排序规则如下:

对于a和b两个数字,如果ab>ba则a应该排在b之前

注意全为0的情况

代码语言:javascript复制
class Solution {
public:
    static bool cmp(string &a, string &b)
    {
        return a b > b a;
    }
    string largestNumber(vector<int>& nums) 
    {
        vector<string> res;
        for(int i = 0; i < nums.size(); i  )
            res.push_back(to_string(nums[i]));
        sort(res.begin(), res.end(), cmp);
        string ans;
        for(int i = 0; i < res.size() ; i  ) ans  = res[i];
        if(ans[0] == '0') ans = '0';
        return ans;
    }
};

0 人点赞