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.
C++代码实现:
#include<iostream> #include<string> #include<vector> using namespace std; class Solution { public: string largestNumber(vector<int> &num) { if(num.empty()) return ""; string ret; int i,j; while(!num.empty()) { i=0; for(j=1;j<(int)num.size();j++) { if((to_string(num[i])+to_string(num[j]))<(to_string(num[j])+to_string(num[i]))) i=j; } ret+=to_string(num[i]); num.erase(num.begin()+i); } while(ret.size()>1&&ret[0]=='0') ret.erase(ret.begin()); return ret; } }; int main() { Solution s; vector<int> vec={3,30,34,5,9}; cout<<s.largestNumber(vec)<<endl; }
直接调用STL算法进行排序:
#include<iostream> #include<vector> #include<string> #include<algorithm> using namespace std; //不能声明non-static成员函数 bool Mycmp(int n1,int n2) { string s1=to_string(n1); string s2=to_string(n2); return s1+s2>s2+s1; } class Solution { public: string largestNumber(vector<int> &num) { if(num.empty()) return ""; string ret=""; sort(num.begin(),num.end(),Mycmp); //sort(num.begin(),num.end(),[](int n1,int n2){ return to_string(n1)+to_string(n2)>to_string(n2)+to_string(n1);}); if(num[0]==0) return "0"; for(auto a:num) ret+=to_string(a); return ret; }
//声明为static成员是可以的
static bool Mycmp(int n1,int n2) { string s1=to_string(n1); string s2=to_string(n2); return s1+s2>s2+s1; }
};
int main()
{
Solution s;
vector<int> num= {3,32,321};
cout<<s.largestNumber(num)<<endl;
}