首页 > 学院 > 开发设计 > 正文

Leetcode 179 Largest Number

2019-11-08 02:32:49
字体:
来源:转载
供稿:网友

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的情况

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;    }};


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表