贪心
每轮找出剩下的数中应该放在最前面的那个数。
即遍历数组,每次保留pos和nums[i]拼接时应该放在前面的数。
179. 最大数
class Solution {
public:
int cal[10005][25];
int tot[10005];
bool cmp(int x,int y){
if (y==-1) return true;
int tip=tot[x]+tot[y]+1;
for (int i=0;i<=tip;i++){
int x1=(tot[x]-i+tot[x]+1)%(tot[x]+1);
int y1=(tot[y]-i+tot[y]+1)%(tot[y]+1);
if (cal[x][x1]>cal[y][y1]) return true;
else if (cal[x][x1]<cal[y][y1]) return false;
}
return false;
}
string largestNumber(vector<int>& nums) {
int tip=nums.size();
for (int i=0;i<tip;i++){
int cnt=0;
int now=nums[i];
if (now==0){
cal[i][0]=0;
tot[i]=0;
continue;
}
while (now>0){
cal[i][cnt]=now%10;
cnt++;
now/=10;
}
cnt--;
tot[i]=cnt;
}
string ans="";
bool used[tip+5];
memset(used,false,sizeof(used));
for (int i=0;i<tip;i++){
int pos=-1;
for (int j=0;j<tip;j++)
if (!used[j]){
if (cmp(j,pos)){
pos=j;
}
}
used[pos]=true;
for (int j=tot[pos];j>=0;j--){
ans+='0'+cal[pos][j];
}
}
//处理前导0
string finalans="";
bool flag=true;
for (int i=0;i<ans.size();i++){
if (flag && ans[i]=='0' && i<ans.size()-1) continue;
flag=false;
finalans+=ans[i];
}
return finalans;
}
};