牛客题霸 [最大数] C++题解/答案

牛客题霸 [最大数] C++题解/答案

题目描述

给定一个数组由一些非负整数组成,现需要将他们进行排列并拼接,使得最后的结果最大,返回值需要是string类型 否则可能会溢出

题解:

将字符串存入vector中然后sort排序,最后将所以字符串连在一起
但是注意,最前面的字符串不能以0开始,所以先将开头的0筛过

代码:

class Solution {
public:
    /**
     * 最大数
     * @param nums int整型vector 
     * @return string字符串
     */
    string solve(vector<int>& nums) {
        // write code here
        vector<string> str;
        for (int i = 0; i < nums.size(); i++) 
        {
            str.push_back(to_string(nums[i]));
        }
        sort(str.begin(), str.end(), cmp);
        string ans = "";
        int i = 0;
        while (i < str.size()-1 && str[i] == "0") 
        {
            i++;
        }
        while (i < str.size()) 
        {
            ans += str[i];
            i++;
        }
        return ans;
    }
     
    static bool cmp(string a, string b) 
    {
        return a+b > b+a;
    }
};
posted @ 2020-12-02 18:30  回归梦想  阅读(293)  评论(0编辑  收藏  举报