Largest Number leetcode

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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

 

Subscribe to see which companies asked this question

 
奋战一个半小时,终于解出来了,运行结果很满意,达到了最快速度,兴奋~~
思路:
1.重点在排序的比较函数,这个不言而喻,但是比较数字是比较最高位,求最高位需要循环,很费时间
2.试着将所有数字都放入一个字符串中,结果发现有问题,因为原来的多位数字都被拆分破坏了
3.试着将单个数字转化为字符串,并放入字符串数组中,可行
4.开始编写比较函数,方法我想了很长时间,其实很简单 return s1 + s2 < s2 + s1就行了,但是我想出来了其他方法,代码如下:
 
string largestNumber(vector<int>& nums) {
    vector<string> vec;
    for (auto num : nums)
        vec.push_back(to_string(num));
    sort(vec.begin(), vec.end(), [](const string &a, const string &b) 
    { 
        int i = 0, j = 0;
        int tag1 = 0, tag2 = 0;
        while (tag1 < 2 && tag2 < 2)
        {
            if (i == a.length()) {
                i = 0;
                tag1++;
            }
                
            if (j == b.length()) {
                j = 0;
                tag2++;
            }
            if (a[i] < b[j])
                return false;
            else if (a[i] > b[j])
                return true;
            i++; j++;
        }
        return false;
    });

    string res;
    for (auto kit : vec)
        res.append(kit);
    if (res.find_first_not_of('0') == -1)
        res = "0";
    return res;
}
原文地址:https://www.cnblogs.com/sdlwlxf/p/5158849.html