题目
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.
题目来自于:https://leetcode.com/problems/largest-number/
分析
这个题目其实是个排序题。把数字转化成字符串,一个字符一个字符的比较。为了偷懒也不用自己实现排序算法,直接用stl里面的sort()函数简单又方便。但是比较的函数得自己定义。
定义排序的时候直觉来看应该首选倒序排列。一个字符一个字符比较,当长度不一致时,将长字符串剩余部分重新与短字符串相比较。
代码
class Solution {
public:
static bool Comp(const int &a, const int &b){
string aa = to_string(a);
string bb = to_string(b);
if(aa == bb)
return false;
int lena = aa.length();
int lenb = bb.length();
int ia = 0;
int ib = 0;
while(ia < lena && ib < lenb){
if(aa[ia] < bb[ib])
return false;
else if(aa[ia] > bb[ib])
return true;
else{
ia++;
ib++;
}
}
if(lena == lenb)
return false;
if(ia < lena){
if(aa[ia] == '0')//整数的最高位肯定不会是0,b转化成字符串后第一个字符肯定大于'0'
return false;
else
return Comp(atoi(aa.substr(ia).c_str()), b);
}
if(ib < lenb){
if(bb[ib] == '0')
return true;
else
return Comp(b, atoi(bb.substr(ib).c_str()));
}
}
string largestNumber(vector<int>& nums) {
sort(nums.begin(), nums.end(), Comp);
string result;
int size = nums.size();
for(int i = 0;i < size; i++){
result += to_string(nums[i]);
}
if(result[0] != '0')
return result;
else
return "0";
}
};
一楼的中年大叔提出了另外一个实现Comp函数的方法:
比较2和21哪个大时可以比较221和212的大小。221 > 212则推出2应该大于21.
static bool Comp(const int &a, const int &b){
string ab = to_string(a) + to_string(b);
string ba = to_string(b) + to_string(a);
if(ab == ba)
return false;
int len = ab.length();
for(int i = 0; i < len; i++){
if(ab[i] > ba[i])
return true;
else if(ab[i] < ba[i])
return false;
}
return false;
}
3634

被折叠的 条评论
为什么被折叠?



