Given a list of non negative integers, arrange them such that they
form the largest number.
Example
Given [1, 20, 23, 4, 8], the largest formed number is 8423201.
Note
The result may be very large, so you need to return a string instead of an integer.
Challenge
Do it in O(nlogn) time complexity.
对于两个备选数字a和b, 如果str(a) + str(b) > str(b) + str(b), 则a在b之前,否则b在a之前,按照这个原则对原数组从大到小排序即可。
有几个问题:
1.注意全部是0的情况
2.cmp函数要设为static
因为:非静态成员函数是依赖于具体对象的,而std::sort这类函数是全局的,因此无法再sort中调用非静态成员函数。静态成员函数或者全局函数是不依赖于具体对象的, 可以独立访问,无须创建任何对象实例就可以访问。同时静态成员函数不可以调用类的非静态成员。
3.本程序是用stringstream进行数字到字符串的转化的。但在C++11中已经提供了to_string的全局函数,非常方便。
参见:http://www.cplusplus.com/reference/string/to_string/
和我的博客C++11中的string - to_string/stoi
class Solution {
public:
/**
*@param num: A list of non negative integers
*@return: A string
*/
static bool cmp(int a,int b){
string ab;
string ba;
stringstream ss;
ss<<a<<b;
ab=ss.str();
ss.str("");
ss<<b<<a;
ba=ss.str();
ss.str("");
return ab>ba;
}
string largestNumber(vector<int> &num) {
// write your code here
sort(num.begin(),num.end(),cmp);
if(num[0]==0){
return "0";
}
stringstream ss;
for(int i=0;i<num.size();i++){
ss<<num[i];
}
string res=ss.str();
ss.str("");
return res;
}
};