179. Largest Number

Given a list of non negative integers, arrange them such that they form the largest number.

Example 1:

1
2
Input: [10,2]
Output: "210"

Example 2:

1
2
Input: [3,30,34,5,9]
Output: "9534330"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public:
string largestNumber(vector<int>& nums) {
if(nums.empty()){
return "";
}
vector<string> sarr;
for(int i=0;i<nums.size();i++){
sarr.push_back(to_string(nums[i]));
}
sort(sarr.begin(), sarr.end(), compare);
string res = "";
for(int i=0;i<sarr.size();i++){
res += sarr[i];
if(i==0 && sarr[i]=="0"){
break;
}
}
return res;
}
static int compare(string c, string d){
string s1 = c + d;
string s2 = d + c;
return s1 > s2;
}
}

总结:学到一种构造cmp函数的方法.