全排列,超时,知道超时,只是想验证一下。
class Solution { public: string largestNumber(vector<int>& nums) { sort(nums.begin(),nums.end()); string res=""; res=f(nums); while(next_permutation(nums.begin(),nums.end())){ if(res<f(nums)) res=f(nums); } return res; } string f(vector<int>& coll){ string res; for(int i=0;i<coll.size();++i){ ostringstream sss; sss<<coll[i]; res+=sss.str(); } return res; } };
en ,这个也不对
class Solution { public: string largestNumber(vector<int>& nums) { vector<string> coll; for(int i=0;i<nums.size();++i){ ostringstream sss; sss<<nums[i]; coll.push_back(sss.str()); } sort(coll.begin(),coll.end()); string res=""; for(int i=coll.size()-1;i>=0;--i) res+=coll[i]; return res; } };
事实证明,过了点不吃饭真的很危险,又低血糖了。
class Solution { public: string largestNumber(vector<int>& nums) { vector<string> coll; for(int i=0;i<nums.size();++i){ ostringstream sss; sss<<nums[i]; coll.push_back(sss.str()); } string res=""; auto ite=coll.begin(); sort(ite,ite+coll.size(),c); for(int i=coll.size()-1;i>=0;--i) res+=coll[i]; if(res[0] == '0') return "0"; return res; } static bool c(const string a,const string b) { string ab=a+b; string ba=b+a; return ab<ba; } };
更精简的
class Solution { public: string largestNumber(vector<int>& nums) { sort(nums.begin(), nums.end(), [](const int& lhs, const int & rhs){return to_string(lhs) + to_string(rhs) > to_string(rhs) + to_string(lhs);}); if (nums[0] == 0) return "0"; return accumulate(nums.begin(), nums.end(), string(""), [](const string& a, int b){ return a + to_string(b);}); } };