Description
Given a list of non negative integers, arrange them such that they form the largest number.
Example 1:
Input: [10,2]
Output: "210"
Example 2:
Input: [3,30,34,5,9]
Output: "9534330"
Note: The result may be very large, so you need to return a string instead of an integer.
分析
题目的意思是:给你一堆数组,然后把它们排列成一个最大的数。
- 重写sort函数来排序,然后把排序结果都拼接起来就行了。
代码
class Solution {
public:
string largestNumber(vector<int>& nums) {
string res;
sort(nums.begin(),nums.end(),[](int a,int b){
return to_string(a)+to_string(b)> to_string(b)+to_string(a);
});
for(int i=0;i<nums.size();i++){
res+=to_string(nums[i]);
}
return res[0]=='0' ? "0":res;
}
};
代码二 (python)
用python实现了一个版本,在构建排序的时候需要借助functools.cmp_to_key函数
class Solution:
def largestNumber(self, nums: List[int]) -> str:
def compare(x, y):
xy = x+y
yx = y+x
if xy>yx:
return 1
elif xy<yx:
return -1
return 0
num_str = [str(num) for num in nums]
num_str.sort(key=cmp_to_key(compare),reverse=True)
largest_num = "".join(num_str)
if(largest_num[0]=='0'):
return '0'
return largest_num