【LeetCode-数组】最大数

题目描述

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

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

输入: [3,30,34,5,9]
输出: 9534330

说明: 输出结果可能非常大,所以你需要返回一个字符串而不是整数。
题目链接: https://leetcode-cn.com/problems/largest-number/

思路

对数组进行排序,排序的规则是:

  • 对于两个数 a 和 b:
    • 如果 str(a)+str(b)>str(b)+str(a),则返回true,保持 a 和 b 的相对顺序不变;
    • 否则,返回 false,交换 a 和 b;

代码如下:

class Solution {
public:

    static bool cmp(int& a, int& b){ // 要用 static
        string ab = to_string(a) + to_string(b);
        string ba = to_string(b) + to_string(a);
        
        return ab>ba;
    }

    string largestNumber(vector<int>& nums) {
        if(nums.empty()) return "";
        if(nums.size()==1) return to_string(nums[0]);

        sort(nums.begin(), nums.end(), cmp);
        string ans = "";
        for(int i=0; i<nums.size(); i++) ans += to_string(nums[i]);

        if(ans[0]=='0') return "0"; // 防止 nums = [0, 0, 0] 的情况
        else return ans;
    }
};

注意比较函数 cmp 要是 static 型的,因为std::sort是属于全局的,无法调用非静态成员函数,而静态成员函数或全局函数是不依赖于具体对象,可以独立访问。

posted @ 2020-07-14 20:04  Flix  阅读(199)  评论(0编辑  收藏  举报