LeetCode-179-Largest Number

算法描述:

Given a list of non negative integers, arrange them such that they form the largest number.

Example 1:

Input: [10,2]
Output: "210"

Example 2:

Input: [3,30,34,5,9]
Output: "9534330"

Note: The result may be very large, so you need to return a string instead of an integer.

解题思路:转化为一个排序题。

    static bool cmp(int a, int b){
        string sa = to_string(a);
        string sb = to_string(b);
        return sa + sb > sb + sa;
        
    }
    string largestNumber(vector<int>& nums) {
        sort(nums.begin(),nums.end(),cmp);
        string res = "";
        for(auto num:nums){
            res += to_string(num);
        }
        while(res.size()>1){
            if(res[0]=='0') res = res.substr(1);
            else break;
        }
        return res;
    }

猜你喜欢

转载自www.cnblogs.com/nobodywang/p/10400406.html
今日推荐