#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
string largestNumber(vector<int>& nums) {
vector<string> numStrs;
for(auto it = nums.begin(); it != nums.end(); it++){
/*stringstream ss;
ss << *it;
string ns;
ss >> ns;
numStrs.push_back(ns);*/
ostringstream oss;
oss << *it;
numStrs.push_back(oss.str());
}
/*sort(numStrs.begin(), numStrs.end(),[](const string& a, const string& b){
int len = min(a.length(), b.length());
int i;
for(i = 0; i < len; i++){
if(a[i] == b[i]) continue;
else return a[i] > b[i];
}
if(i == len) return a.length() > b.length();
});*/
sort(numStrs.begin(), numStrs.end(), [](const string& a, const string& b){
string ab(a+b), ba(b+a);
for(int i = 0; i < ab.length(); i++){
if(ab[i] == ba[i]) continue;
return ab[i] > ba[i];
}
return false; //!!这里必须有返回值,并且不能写true,否则会运行时错误!!!
});
string ret;
if(*numStrs.begin() == "0") //特判,如果全是0,返回0。否则会得到"00...0"
return "0";
for(auto it = numStrs.begin(); it != numStrs.end(); it++){
ret += *it;
}
return ret;
}
/*string largestNumber2(vector<int>& nums) {
int N = nums.size();
vector<string> numStrs(N);
for(int i = 0; i < N; i++){
stringstream ss;
ss << nums[i];
string ns;
ss >> ns;
numStrs[i] = ns;
}
sort(numStrs.begin(), numStrs.end(), cmp);
string ret = numStrs[0];
if(ret != "0")
for(int i = 1; i < N; i++) ret += numStrs[i];
return ret;
}
*/
};
int main(){
Solution sol;
int arr[5] = {34, 25,10, 17, 19};
cout << sizeof(arr) << endl;
vector<int> var({2,2,2});
cout << sol.largestNumber(var) << endl;
}
[Leetcode] Largest Number
最新推荐文章于 2021-04-12 08:43:55 发布