[LeetCode]179. 最大数

贪心
每轮找出剩下的数中应该放在最前面的那个数。
即遍历数组,每次保留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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值