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.
关键在于定义一种新的字符串比较规则,使得我们把排序好的字符串数组串一遍就能得到结果。
新的比较规则是return s1+s2 < s2+s1;
然后证明这种比较规则为什么是对的。
证明:
假设按这种规则排序好的数组是:A1,A2,A3...Ax....Ay.....An
根据这种排序规则,最后的排序结果是An...AyAy-1...Ax...A3A2A1
反证法证明:
假设存在一个An...AxAy-1...Ay...A3A2A1 > An...AyAy-1...Ax...A3A2A1
由于Ax<Ax+1<Ax+2<Ax+3<....<Ay-1<Ay
那么An...Ay Ay-1... Ax+2 Ax+1 Ax...A3 A2 A1 > An...AyAy-1...Ax Ax+1...A3A2A1,这是根据比较规则来的,比较规则中,若Ax<Ax+1则AxAx+1 < Ax+1Ax
同样An...AyAy-1...Ax Ax+1...A3A2A1 > An...AyAy-1...Ax Ax+2 Ax+1...A3A2A1>...>An...Ax Ay Ay-1...Ax+2 Ax+1...A3A2A1。
同理可以证明An...Ax Ay Ay-1...Ax+2 Ax+1...A3A2A1>An...Ax Ay-1...Ax+1 Ay...A3A2A1。
这就与假设相反,所以得证
bool comp(const string& lhs,const string& rhs){ return lhs+rhs < rhs+lhs; } class Solution { public: string largestNumber(vector<int>& nums) { vector<string> str_nums; //以下三种整数转字符串 /*1. for(auto num:nums){ char buf[20]={0}; sprintf(buf,"%d",num); str_nums.push_back(string(buf)); } */ /*2. vector<string> str_nums(nums.size()); stringsteam stream; for(auto num:nums){ stream<<num; stream>>str_nums[i]; str_nums.push_back(string(buf)); } */ for(auto num:nums){ str_nums.push_back(to_string(num)); } sort(str_nums.begin(),str_nums.end(),comp); string res; for(int i=str_nums.size()-1;i>=0;i--){ res.append(str_nums[i].begin(),str_nums[i].end()); } return (res.empty() || res[0]!='0' )? res : "0"; } };