leetcode 179. 最大数

问题描述

给定一组非负整数,重新排列它们的顺序使之组成一个最大的整数。

示例 1:

输入: [10,2]
输出: 210
示例 2:

输入: [3,30,34,5,9]
输出: 9534330
说明: 输出结果可能非常大,所以你需要返回一个字符串而不是整数。

代码

class Solution {
public:
    string largestNumber(vector<int>& nums) {
        string ans;
        int n = nums.size(),i,tmp;
        sort(nums.begin(),nums.end(),Comp);
        for(i = 0; i < n; i++)
        {
            ans += to_string(nums[i]);
        }
        return ans[0]=='0'?"0":ans;
    }
    static bool Comp(const int& a,const int& b)
    {
        return to_string(a)+to_string(b) > to_string(b)+to_string(a);
    }
};

结果:

执行用时 :20 ms, 在所有 C++ 提交中击败了35.16%的用户
内存消耗 :12.4 MB, 在所有 C++ 提交中击败了5.00%的用户

其中我们使用static原因见博客.

posted @ 2020-03-24 08:31  曲径通霄  阅读(87)  评论(0编辑  收藏  举报