179. Largest Number(INT, String)

时间:2023-03-08 15:51:52

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.

思路:

要对数字进行排列,首位大的在前。

比较每个数字的首位,这在不知道位数的情况下,很难实现,所以将INT转换成string再比较。

由于string的连接操作非常方便,所以比较首位的大小,可以转化成比较连接后string的大小。

class Solution {
public:
static bool cmp(const string &s1, const string &s2){ //注意static,const,引用的使用
return (s1+s2) > (s2+s1); // >表示按降序排列
}
string largestNumber(vector<int>& nums) {
int size = nums.size();
stringstream ss;
vector<string> s_nums(size);
string ret = ""; for(int i = ; i < size; i++){
ss << nums[i];
ss >> s_nums[i];
ss.clear();
}
sort(s_nums.begin(), s_nums.end(),cmp); if(s_nums[]=="") return s_nums[];
for(int i = ; i < size; i++){
ret += s_nums[i];
}
return ret;
}
};