[LeetCode]Largest Number

题目描述:

Largest Number

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.

解题思路:

1. 题目要求用所给的整数排出最大的数;

2. 基本的思想是使用排序的办法,按照一定的方法把所给出的整数排序,排序后的结果按顺序连起来就是最大的整数。

3. 使用的排序是快排函数sort,重载sort使用自己设计的排序方案:对所给的2个整数进行1+2和2+1的字符串连接,找出其中字符串大的连接方式。

解题代码:

class Solution {
public:
    bool static get_large(int num1, int num2)
    {
        string s1 = to_string(num1) + to_string(num2);
        string s2 = to_string(num2) + to_string(num1);
        
        return (s1.compare(s2) > 0);
    }
    string largestNumber(vector<int> &num) {
        string result = "";
        sort(num.begin(), num.end(), get_large);
        for(int i = 0; i < num.size(); i++)
        {
            result += to_string(num[i]);
        }
        
        if(result[0] == '0')return "0";
        return result;
    }

};
原文地址:https://www.cnblogs.com/liuyikang/p/4351134.html