将数组中的元素进行重排,组成最大的数。
如果只有两个数,可以简单判断:,使用贪心,将数组中的元素按照上述比较规则进行降序排序,进行拼接即为所求。证明如下:
假设按照贪心得到的最优解为:(其中
有
位,
有
位,
)。若存在解
(
和
交换位置)比
更优。令
右边有
位,则有:
,与假设矛盾。因此贪心为最优解。代码如下:
class Solution {
public:
string largestNumber(vector<int>& nums) {
sort(nums.begin(), nums.end(), CMP());
if(nums[0] == 0)
return "0";
string ans = "";
int len = nums.size();
for(int i = 0; i < len; ++i){
ans += to_string(nums[i]);
}
return ans;
}
private:
struct CMP{
bool operator()(const int& a, const int& b){
long long ans1 = 10, ans2 = 10;
int n1 = a / 10, n2 = b / 10;
while(n1)
ans1 *= 10, n1 /= 10;
while(n2)
ans2 *= 10, n2 /= 10;
return ans2 * a + b > ans1 * b + a;
}
};
};