第73题 Largest Number

来源:互联网 发布:域名在哪买都是一样的 编辑:程序博客网 时间:2024/06/10 02:10

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.

Hide Tags
 Sort









Solution in C++:
class Solution {public:    string largestNumber(vector<int>& nums) {        sort(nums.begin(), nums.end(), Compare);        if(nums[nums.size()-1]==0||nums.size()==0) return "0";        string solution = "";                for(int i=nums.size()-1; i>= 0; i--){            solution+= to_string(nums[i]);        }        return solution;            }    static bool Compare(const int &a, const int &b){        string strA = to_string(a);        string strB = to_string(b);        if(strA.size()==strB.size()) return a<b;        int digit=0;        while(digit<strA.size()&&digit<strB.size()){            if(strA[digit]-'0'<strB[digit]-'0') return true;            if(strA[digit]-'0'>strB[digit]-'0') return false;            digit++;        }        if(digit<strA.size()){            if(strA[digit]=='0') return true;            return Compare(atoi(strA.substr(digit).c_str()), b);        }         if(digit<strB.size()){            if(strB[digit]=='0') return false;            return Compare(a, atoi(strB.substr(digit).c_str()));        }     }};



Note: 如果排完序后最大数为0,说明数组里所有数都是0,要返回“0”。
atoi是c里面的函数,参数必须是const char*,所以要把字符串c_str()一下。
C++中substr函数参数为(起始index,substring长度),所以endindex = startIndex+length-1
Compare函数必须是static bool类型,<返回true,>=返回false。
当两数从左数i位都相同,调用递归时,因为atoi函数会将最前面的0省略,而如果获得的substr从0开始时,比任何其他不从0开始的数排序都应该小,所以strA[digit]和strB[digit]为‘0’时,直接返回。
0 0